repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.secgroup_create
python
def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret
Create a security group
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1083-L1090
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.secgroup_delete
python
def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name)
Delete a security group
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1092-L1101
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.secgroup_list
python
def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret
List security groups
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1103-L1117
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova._item_list
python
def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret
List items
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1119-L1127
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova._network_show
python
def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {}
Parse the returned network list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1129-L1136
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.network_show
python
def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list)
Show network information
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1138-L1144
[ "def _network_show(self, name, network_lst):\n '''\n Parse the returned network list\n '''\n for net in network_lst:\n if net.label == name:\n return net.__dict__\n return {}\n" ]
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.network_list
python
def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()]
List extra private networks
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1146-L1151
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova._sanatize_network_params
python
def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs
Sanatize novaclient network parameters
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1153-L1166
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n" ]
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.network_create
python
def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__
Create extra private network
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1168-L1176
[ "def _sanatize_network_params(self, kwargs):\n '''\n Sanatize novaclient network parameters\n '''\n params = [\n 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',\n 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',\n 'priority', 'project_id', 'vlan_start', 'vpn_start'\n ]\n\n for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some\n if variable not in params:\n del kwargs[variable]\n return kwargs\n" ]
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.virtual_interface_list
python
def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets]
Get virtual interfaces on slice
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1184-L1190
[ "def _server_uuid_from_name(self, name):\n '''\n Get server uuid from name\n '''\n return self.server_list().get(name, {}).get('id', '')\n" ]
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.virtual_interface_create
python
def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets
Add an interfaces to a slice
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1192-L1202
[ "def network_show(self, name):\n '''\n Show network information\n '''\n nt_ks = self.compute_conn\n net_list = nt_ks.networks.list()\n return self._network_show(name, net_list)\n", "def _server_uuid_from_name(self, name):\n '''\n Get server uuid from name\n '''\n return self.server_list().get(name, {}).get('id', '')\n" ]
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.floating_ip_pool_list
python
def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response
List all floating IP pools .. versionadded:: 2016.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1204-L1217
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.floating_ip_list
python
def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response
List floating IPs .. versionadded:: 2016.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1219-L1236
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.floating_ip_create
python
def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response
Allocate a floating IP .. versionadded:: 2016.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1258-L1273
null
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.floating_ip_delete
python
def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip)
De-allocate a floating IP .. versionadded:: 2016.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1275-L1283
[ "def floating_ip_show(self, ip):\n '''\n Show info on specific floating IP\n\n .. versionadded:: 2016.3.0\n '''\n nt_ks = self.compute_conn\n floating_ips = nt_ks.floating_ips.list()\n for floating_ip in floating_ips:\n if floating_ip.ip == ip:\n response = {\n 'ip': floating_ip.ip,\n 'fixed_ip': floating_ip.fixed_ip,\n 'id': floating_ip.id,\n 'instance_id': floating_ip.instance_id,\n 'pool': floating_ip.pool\n }\n return response\n return {}\n" ]
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip] def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.floating_ip_associate
python
def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
Associate floating IP address to server .. versionadded:: 2016.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1285-L1295
[ "def server_by_name(self, name):\n '''\n Find a server by its name\n '''\n return self.server_show_libcloud(\n self.server_list().get(name, {}).get('id', '')\n )\n", "def floating_ip_list(self):\n '''\n List floating IPs\n\n .. versionadded:: 2016.3.0\n '''\n nt_ks = self.compute_conn\n floating_ips = nt_ks.floating_ips.list()\n response = {}\n for floating_ip in floating_ips:\n response[floating_ip.ip] = {\n 'ip': floating_ip.ip,\n 'fixed_ip': floating_ip.fixed_ip,\n 'id': floating_ip.id,\n 'instance_id': floating_ip.instance_id,\n 'pool': floating_ip.pool\n }\n return response\n" ]
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/utils/openstack/nova.py
SaltNova.floating_ip_disassociate
python
def floating_ip_disassociate(self, server_name, floating_ip): ''' Disassociate a floating IP from server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.remove_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
Disassociate a floating IP from server .. versionadded:: 2016.3.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1297-L1307
[ "def server_by_name(self, name):\n '''\n Find a server by its name\n '''\n return self.server_show_libcloud(\n self.server_list().get(name, {}).get('id', '')\n )\n", "def floating_ip_list(self):\n '''\n List floating IPs\n\n .. versionadded:: 2016.3.0\n '''\n nt_ks = self.compute_conn\n floating_ips = nt_ks.floating_ips.list()\n response = {}\n for floating_ip in floating_ips:\n response[floating_ip.ip] = {\n 'ip': floating_ip.ip,\n 'fixed_ip': floating_ip.fixed_ip,\n 'id': floating_ip.id,\n 'instance_id': floating_ip.instance_id,\n 'pool': floating_ip.pool\n }\n return response\n" ]
class SaltNova(object): ''' Class for all novaclient functions ''' extensions = [] def __init__( self, username, project_id, auth_url, region_name=None, password=None, os_auth_plugin=None, use_keystoneauth=False, **kwargs ): ''' Set up nova credentials ''' if all([use_keystoneauth, HAS_KEYSTONEAUTH]): self._new_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) else: self._old_init(username=username, project_id=project_id, auth_url=auth_url, region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, **kwargs) def _get_version_from_url(self, url): ''' Exctract API version from provided URL ''' regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$") try: ver = regex.match(url) if ver.group(1): retver = ver.group(1) if ver.group(2): retver = retver + ver.group(2) return retver except AttributeError: return '' def _discover_ks_version(self, url): ''' Keystone API version discovery ''' result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json') versions = json.loads(result['body']) try: links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \ if result['status'] == 300 else versions['version']['links'] resurl = [link['href'] for link in links if link['rel'] == 'self'][0] return self._get_version_from_url(resurl) except KeyError as exc: raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions)) def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs): if auth is None: auth = {} ks_version = self._get_version_from_url(auth_url) if not ks_version: ks_version = self._discover_ks_version(auth_url) auth_url = '{0}/{1}'.format(auth_url, ks_version) loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password') self.client_kwargs = kwargs.copy() self.kwargs = auth.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.client_kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_name'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['password'] = password if ks_version == 'v3': self.kwargs['project_id'] = kwargs.get('project_id') self.kwargs['project_name'] = kwargs.get('project_name') self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default') self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default') self.client_kwargs['region_name'] = region_name self.client_kwargs['service_type'] = 'compute' if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.client_kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.client_kwargs = self.kwargstruct.__dict__ # Requires novaclient version >= 2.6.1 self.version = six.text_type(kwargs.get('version', 2)) self.client_kwargs = sanatize_novaclient(self.client_kwargs) options = loader.load_from_options(**self.kwargs) self.session = keystoneauth1.session.Session(auth=options) conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) self.kwargs['auth_token'] = conn.client.session.get_token() identity_service_type = kwargs.get('identity_service_type', 'identity') self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog', endpoint_filter={'service_type': identity_service_type} ).json().get('catalog', []) for ep_type in self.catalog: if ep_type['type'] == identity_service_type: for ep_id in ep_type['endpoints']: ep_ks_version = self._get_version_from_url(ep_id['url']) if not ep_ks_version: ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version) if ks_version == 'v3': self._v3_setup(region_name) else: self._v2_setup(region_name) def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs): self.kwargs = kwargs.copy() if not self.extensions: if hasattr(OpenStackComputeShell, '_discover_extensions'): self.extensions = OpenStackComputeShell()._discover_extensions('2.0') else: self.extensions = client.discover_extensions('2.0') for extension in self.extensions: extension.run_hooks('__pre_parse_args__') self.kwargs['extensions'] = self.extensions self.kwargs['username'] = username self.kwargs['project_id'] = project_id self.kwargs['auth_url'] = auth_url self.kwargs['region_name'] = region_name self.kwargs['service_type'] = 'compute' # used in novaclient extensions to see if they are rackspace or not, to know if it needs to load # the hooks for that extension or not. This is cleaned up by sanatize_novaclient self.kwargs['os_auth_url'] = auth_url if os_auth_plugin is not None: novaclient.auth_plugin.discover_auth_systems() auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin) self.kwargs['auth_plugin'] = auth_plugin self.kwargs['auth_system'] = os_auth_plugin if not self.kwargs.get('api_key', None): self.kwargs['api_key'] = password # This has to be run before sanatize_novaclient before extra variables are cleaned out. if hasattr(self, 'extensions'): # needs an object, not a dictionary self.kwargstruct = KwargsStruct(**self.kwargs) for extension in self.extensions: extension.run_hooks('__post_parse_args__', self.kwargstruct) self.kwargs = self.kwargstruct.__dict__ self.kwargs = sanatize_novaclient(self.kwargs) # Requires novaclient version >= 2.6.1 self.kwargs['version'] = six.text_type(kwargs.get('version', 2)) conn = client.Client(**self.kwargs) try: conn.client.authenticate() except novaclient.exceptions.AmbiguousEndpoints: raise SaltCloudSystemExit( "Nova provider requires a 'region_name' to be specified" ) self.kwargs['auth_token'] = conn.client.auth_token self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog'] self._v2_setup(region_name) def _v3_setup(self, region_name): if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name) log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url']) self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name) log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url']) self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def _v2_setup(self, region_name): if region_name is not None: servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints'] self.kwargs['bypass_url'] = get_entry( servers_endpoints, 'region', region_name )['publicURL'] self.compute_conn = client.Client(**self.kwargs) volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {}) if volume_endpoints: if region_name is not None: self.kwargs['bypass_url'] = get_entry( volume_endpoints, 'region', region_name )['publicURL'] self.volume_conn = client.Client(**self.kwargs) if hasattr(self, 'extensions'): self.expand_extensions() else: self.volume_conn = None def expand_extensions(self): for connection in (self.compute_conn, self.volume_conn): if connection is None: continue for extension in self.extensions: for attr in extension.module.__dict__: if not inspect.isclass(getattr(extension.module, attr)): continue for key, value in six.iteritems(connection.__dict__): if not isinstance(value, novaclient.base.Manager): continue if value.__class__.__name__ == attr: setattr(connection, key, extension.manager_class(connection)) def get_catalog(self): ''' Return service catalog ''' return self.catalog def server_show_libcloud(self, uuid): ''' Make output look like libcloud output for consistency ''' server_info = self.server_show(uuid) server = next(six.itervalues(server_info)) server_name = next(six.iterkeys(server_info)) if not hasattr(self, 'password'): self.password = None ret = NovaServer(server_name, server, self.password) return ret def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) block_device = kwargs.pop('block_device', []) boot_volume = kwargs.pop('boot_volume', None) snapshot = kwargs.pop('snapshot', None) swap = kwargs.pop('swap', None) kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2( block_device=block_device, boot_volume=boot_volume, snapshot=snapshot, ephemeral=ephemeral, swap=swap ) response = nt_ks.servers.create(**kwargs) self.uuid = response.id self.password = getattr(response, 'adminPass', None) start = time.time() trycount = 0 while True: trycount += 1 try: return self.server_show_libcloud(self.uuid) except Exception as exc: log.debug( 'Server information not yet available: %s', exc ) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying server_show() (try %s)', trycount ) def show_instance(self, name): ''' Find a server by its name (libcloud) ''' return self.server_by_name(name) def root_password(self, server_id, password): ''' Change server(uuid's) root password ''' nt_ks = self.compute_conn nt_ks.servers.change_password(server_id, password) def server_by_name(self, name): ''' Find a server by its name ''' return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') ) def _volume_get(self, volume_id): ''' Organize information about a volume from the volume_id ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volume = nt_ks.volumes.get(volume_id) response = {'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_list(self, search_opts=None): ''' List all block volumes ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = nt_ks.volumes.list(search_opts=search_opts) response = {} for volume in volumes: response[volume.display_name] = { 'name': volume.display_name, 'size': volume.size, 'id': volume.id, 'description': volume.display_description, 'attachments': volume.attachments, 'status': volume.status } return response def volume_show(self, name): ''' Show one volume ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn volumes = self.volume_list( search_opts={'display_name': name}, ) volume = volumes[name] # except Exception as esc: # # volume doesn't exist # log.error(esc.strerror) # return {'name': name, 'status': 'deleted'} return volume def volume_create(self, name, size=100, snapshot=None, voltype=None, availability_zone=None): ''' Create a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn response = nt_ks.volumes.create( size=size, display_name=name, volume_type=voltype, snapshot_id=snapshot, availability_zone=availability_zone ) return self._volume_get(response.id) def volume_delete(self, name): ''' Delete a block device ''' if self.volume_conn is None: raise SaltCloudSystemExit('No cinder endpoint available') nt_ks = self.volume_conn try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if volume['status'] == 'deleted': return volume response = nt_ks.volumes.delete(volume['id']) return volume def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) if not volume['attachments']: return True response = self.compute_conn.volumes.delete_server_volume( volume['attachments'][0]['server_id'], volume['attachments'][0]['id'] ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'available': return response except Exception as exc: log.debug('Volume is detaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %d seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %d)', trycount ) def volume_attach(self, name, server_name, device='/dev/xvdb', timeout=300): ''' Attach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc)) server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume['id'], device=device ) trycount = 0 start = time.time() while True: trycount += 1 try: response = self._volume_get(volume['id']) if response['status'] == 'in-use': return response except Exception as exc: log.debug('Volume is attaching: %s', name) time.sleep(1) if time.time() - start > timeout: log.error('Timed out after %s seconds ' 'while waiting for data', timeout) return False log.debug( 'Retrying volume_show() (try %s)', trycount ) def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True def resume(self, instance_id): ''' Resume a server ''' nt_ks = self.compute_conn response = nt_ks.servers.resume(instance_id) return True def lock(self, instance_id): ''' Lock an instance ''' nt_ks = self.compute_conn response = nt_ks.servers.lock(instance_id) return True def delete(self, instance_id): ''' Delete a server ''' nt_ks = self.compute_conn response = nt_ks.servers.delete(instance_id) return True def flavor_list(self, **kwargs): ''' Return a list of available flavors (nova flavor-list) ''' nt_ks = self.compute_conn ret = {} for flavor in nt_ks.flavors.list(**kwargs): links = {} for link in flavor.links: links[link['rel']] = link['href'] ret[flavor.name] = { 'disk': flavor.disk, 'id': flavor.id, 'name': flavor.name, 'ram': flavor.ram, 'swap': flavor.swap, 'vcpus': flavor.vcpus, 'links': links, } if hasattr(flavor, 'rxtx_factor'): ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor return ret list_sizes = flavor_list def flavor_create(self, name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True): ''' Create a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.create( name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public ) return {'name': name, 'id': flavor_id, 'ram': ram, 'disk': disk, 'vcpus': vcpus, 'is_public': is_public} def flavor_delete(self, flavor_id): # pylint: disable=C0103 ''' Delete a flavor ''' nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) return 'Flavor deleted: {0}'.format(flavor_id) def flavor_access_list(self, **kwargs): ''' Return a list of project IDs assigned to flavor ID ''' flavor_id = kwargs.get('flavor_id') nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def flavor_access_remove(self, flavor_id, project_id): ''' Remove a project from the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id) for project in flavor_accesses: ret[flavor_id].append(project.tenant_id) return ret def keypair_list(self): ''' List keypairs ''' nt_ks = self.compute_conn ret = {} for keypair in nt_ks.keypairs.list(): ret[keypair.name] = { 'name': keypair.name, 'fingerprint': keypair.fingerprint, 'public_key': keypair.public_key, } return ret def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: return False nt_ks.keypairs.create(name, public_key=pubkey) ret = {'name': name, 'pubkey': pubkey} return ret def keypair_delete(self, name): ''' Delete a keypair ''' nt_ks = self.compute_conn nt_ks.keypairs.delete(name) return 'Keypair deleted: {0}'.format(name) def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret['minRam'] = image.minRam return ret def image_list(self, name=None): ''' List server images ''' nt_ks = self.compute_conn ret = {} for image in nt_ks.images.list(): links = {} for link in image.links: links[link['rel']] = link['href'] ret[image.name] = { 'name': image.name, 'id': image.id, 'status': image.status, 'progress': image.progress, 'created': image.created, 'updated': image.updated, 'metadata': image.metadata, 'links': links, } if hasattr(image, 'minDisk'): ret[image.name]['minDisk'] = image.minDisk if hasattr(image, 'minRam'): ret[image.name]['minRam'] = image.minRam if name: return {name: ret[name]} return ret list_images = image_list def image_meta_set(self, image_id=None, name=None, **kwargs): # pylint: disable=C0103 ''' Set image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.set_meta(image_id, kwargs) return {image_id: kwargs} def image_meta_delete(self, image_id=None, # pylint: disable=C0103 name=None, keys=None): ''' Delete image metadata ''' nt_ks = self.compute_conn if name: for image in nt_ks.images.list(): if image.name == name: image_id = image.id # pylint: disable=C0103 pairs = keys.split(',') if not image_id: return {'Error': 'A valid image name or id was not specified'} nt_ks.images.delete_meta(image_id, pairs) return {image_id: 'Deleted: {0}'.format(pairs)} def server_list(self): ''' List servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'id': item.id, 'name': item.name, 'state': item.status, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, } except TypeError: pass return ret def server_list_min(self): ''' List minimal information about servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret def server_list_detailed(self): ''' Detailed list of servers ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(): try: ret[item.name] = { 'OS-EXT-SRV-ATTR': {}, 'OS-EXT-STS': {}, 'accessIPv4': item.accessIPv4, 'accessIPv6': item.accessIPv6, 'addresses': item.addresses, 'created': item.created, 'flavor': {'id': item.flavor['id'], 'links': item.flavor['links']}, 'hostId': item.hostId, 'id': item.id, 'image': {'id': item.image['id'] if item.image else 'Boot From Volume', 'links': item.image['links'] if item.image else ''}, 'key_name': item.key_name, 'links': item.links, 'metadata': item.metadata, 'name': item.name, 'state': item.status, 'tenant_id': item.tenant_id, 'updated': item.updated, 'user_id': item.user_id, } except TypeError: continue ret[item.name]['progress'] = getattr(item, 'progress', '0') if hasattr(item.__dict__, 'OS-DCF:diskConfig'): ret[item.name]['OS-DCF'] = { 'diskConfig': item.__dict__['OS-DCF:diskConfig'] } if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'): ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \ item.__dict__['OS-EXT-SRV-ATTR:host'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'): ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \ item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname'] if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'): ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \ item.__dict__['OS-EXT-SRV-ATTR:instance_name'] if hasattr(item.__dict__, 'OS-EXT-STS:power_state'): ret[item.name]['OS-EXT-STS']['power_state'] = \ item.__dict__['OS-EXT-STS:power_state'] if hasattr(item.__dict__, 'OS-EXT-STS:task_state'): ret[item.name]['OS-EXT-STS']['task_state'] = \ item.__dict__['OS-EXT-STS:task_state'] if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'): ret[item.name]['OS-EXT-STS']['vm_state'] = \ item.__dict__['OS-EXT-STS:vm_state'] if hasattr(item.__dict__, 'security_groups'): ret[item.name]['security_groups'] = \ item.__dict__['security_groups'] return ret def server_show(self, server_id): ''' Show details of one server ''' ret = {} try: servers = self.server_list_detailed() except AttributeError: raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.') for server_name, server in six.iteritems(servers): if six.text_type(server['id']) == server_id: ret[server_name] = server return ret def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret def secgroup_delete(self, name): ''' Delete a security group ''' nt_ks = self.compute_conn for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) return {name: 'Deleted security group: {0}'.format(name)} return 'Security group not found: {0}'.format(name) def secgroup_list(self): ''' List security groups ''' nt_ks = self.compute_conn ret = {} for item in nt_ks.security_groups.list(): ret[item.name] = { 'name': item.name, 'description': item.description, 'id': item.id, 'tenant_id': item.tenant_id, 'rules': item.rules, } return ret def _item_list(self): ''' List items ''' nt_ks = self.compute_conn ret = [] for item in nt_ks.items.list(): ret.append(item.__dict__) return ret def _network_show(self, name, network_lst): ''' Parse the returned network list ''' for net in network_lst: if net.label == name: return net.__dict__ return {} def network_show(self, name): ''' Show network information ''' nt_ks = self.compute_conn net_list = nt_ks.networks.list() return self._network_show(name, net_list) def network_list(self): ''' List extra private networks ''' nt_ks = self.compute_conn return [network.__dict__ for network in nt_ks.networks.list()] def _sanatize_network_params(self, kwargs): ''' Sanatize novaclient network parameters ''' params = [ 'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1', 'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host', 'priority', 'project_id', 'vlan_start', 'vpn_start' ] for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some if variable not in params: del kwargs[variable] return kwargs def network_create(self, name, **kwargs): ''' Create extra private network ''' nt_ks = self.compute_conn kwargs['label'] = name kwargs = self._sanatize_network_params(kwargs) net = nt_ks.networks.create(**kwargs) return net.__dict__ def _server_uuid_from_name(self, name): ''' Get server uuid from name ''' return self.server_list().get(name, {}).get('id', '') def virtual_interface_list(self, name): ''' Get virtual interfaces on slice ''' nt_ks = self.compute_conn nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name)) return [network.__dict__ for network in nets] def virtual_interface_create(self, name, net_name): ''' Add an interfaces to a slice ''' nt_ks = self.compute_conn serverid = self._server_uuid_from_name(name) networkid = self.network_show(net_name).get('id', None) if networkid is None: return {net_name: False} nets = nt_ks.virtual_interfaces.create(networkid, serverid) return nets def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': pool.name, } return response def floating_ip_list(self): ''' List floating IPs .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() response = {} for floating_ip in floating_ips: response[floating_ip.ip] = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_show(self, ip): ''' Show info on specific floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ips = nt_ks.floating_ips.list() for floating_ip in floating_ips: if floating_ip.ip == ip: response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response return {} def floating_ip_create(self, pool=None): ''' Allocate a floating IP .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn floating_ip = nt_ks.floating_ips.create(pool) response = { 'ip': floating_ip.ip, 'fixed_ip': floating_ip.fixed_ip, 'id': floating_ip.id, 'instance_id': floating_ip.instance_id, 'pool': floating_ip.pool } return response def floating_ip_delete(self, floating_ip): ''' De-allocate a floating IP .. versionadded:: 2016.3.0 ''' ip = self.floating_ip_show(floating_ip) nt_ks = self.compute_conn return nt_ks.floating_ips.delete(ip) def floating_ip_associate(self, server_name, floating_ip): ''' Associate floating IP address to server .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn server_ = self.server_by_name(server_name) server = nt_ks.servers.get(server_.__dict__['id']) server.add_floating_ip(floating_ip) return self.floating_ip_list()[floating_ip]
saltstack/salt
salt/version.py
dependency_information
python
def dependency_information(include_salt_cloud=False): ''' Report versions of library dependencies. ''' libs = [ ('Python', None, sys.version.rsplit('\n')[0].strip()), ('Jinja2', 'jinja2', '__version__'), ('M2Crypto', 'M2Crypto', 'version'), ('msgpack-python', 'msgpack', 'version'), ('msgpack-pure', 'msgpack_pure', 'version'), ('pycrypto', 'Crypto', '__version__'), ('pycryptodome', 'Cryptodome', 'version_info'), ('PyYAML', 'yaml', '__version__'), ('PyZMQ', 'zmq', '__version__'), ('ZMQ', 'zmq', 'zmq_version'), ('Mako', 'mako', '__version__'), ('Tornado', 'tornado', 'version'), ('timelib', 'timelib', 'version'), ('dateutil', 'dateutil', '__version__'), ('pygit2', 'pygit2', '__version__'), ('libgit2', 'pygit2', 'LIBGIT2_VERSION'), ('smmap', 'smmap', '__version__'), ('cffi', 'cffi', '__version__'), ('pycparser', 'pycparser', '__version__'), ('gitdb', 'gitdb', '__version__'), ('gitpython', 'git', '__version__'), ('python-gnupg', 'gnupg', '__version__'), ('mysql-python', 'MySQLdb', '__version__'), ('cherrypy', 'cherrypy', '__version__'), ('docker-py', 'docker', '__version__'), ] if include_salt_cloud: libs.append( ('Apache Libcloud', 'libcloud', '__version__'), ) for name, imp, attr in libs: if imp is None: yield name, attr continue try: imp = __import__(imp) version = getattr(imp, attr) if callable(version): version = version() if isinstance(version, (tuple, list)): version = '.'.join(map(str, version)) yield name, version except Exception: yield name, None
Report versions of library dependencies.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/version.py#L574-L624
null
# -*- coding: utf-8 -*- ''' Set up the version of Salt ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import re import sys import platform import warnings # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # pylint: disable=invalid-name,redefined-builtin # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import map # Don't rely on external packages in this module since it's used at install time if sys.version_info[0] == 3: MAX_SIZE = sys.maxsize string_types = (str,) else: MAX_SIZE = sys.maxint string_types = (six.string_types,) # pylint: enable=invalid-name,redefined-builtin # ----- ATTENTION ---------------------------------------------------------------------------------------------------> # # ALL major version bumps, new release codenames, MUST be defined in the SaltStackVersion.NAMES dictionary, i.e.: # # class SaltStackVersion(object): # # NAMES = { # 'Hydrogen': (2014, 1), # <- This is the tuple to bump versions # ( ... ) # } # # # ONLY UPDATE CODENAMES AFTER BRANCHING # # As an example, The Helium codename must only be properly defined with "(2014, 7)" after Hydrogen, "(2014, 1)", has # been branched out into it's own branch. # # ALL OTHER VERSION INFORMATION IS EXTRACTED FROM THE GIT TAGS # # <---- ATTENTION ---------------------------------------------------------------------------------------------------- class SaltStackVersion(object): ''' Handle SaltStack versions class. Knows how to parse ``git describe`` output, knows about release candidates and also supports version comparison. ''' __slots__ = ('name', 'major', 'minor', 'bugfix', 'mbugfix', 'pre_type', 'pre_num', 'noc', 'sha') git_describe_regex = re.compile( r'(?:[^\d]+)?(?P<major>[\d]{1,4})' r'\.(?P<minor>[\d]{1,2})' r'(?:\.(?P<bugfix>[\d]{0,2}))?' r'(?:\.(?P<mbugfix>[\d]{0,2}))?' r'(?:(?P<pre_type>rc|a|b|alpha|beta|nb)(?P<pre_num>[\d]{1}))?' r'(?:(?:.*)-(?P<noc>(?:[\d]+|n/a))-(?P<sha>[a-z0-9]{8}))?' ) git_sha_regex = r'(?P<sha>[a-z0-9]{7})' if six.PY2: git_sha_regex = git_sha_regex.decode(__salt_system_encoding__) git_sha_regex = re.compile(git_sha_regex) # Salt versions after 0.17.0 will be numbered like: # <4-digit-year>.<month>.<bugfix> # # Since the actual version numbers will only be know on release dates, the # periodic table element names will be what's going to be used to name # versions and to be able to mention them. NAMES = { # Let's keep at least 3 version names uncommented counting from the # latest release so we can map deprecation warnings to versions. # pylint: disable=E8203 # ----- Please refrain from fixing PEP-8 E203 and E265 -----> # The idea is to keep this readable. # ----------------------------------------------------------- 'Hydrogen' : (2014, 1), 'Helium' : (2014, 7), 'Lithium' : (2015, 5), 'Beryllium' : (2015, 8), 'Boron' : (2016, 3), 'Carbon' : (2016, 11), 'Nitrogen' : (2017, 7), 'Oxygen' : (2018, 3), 'Fluorine' : (2019, 2), 'Neon' : (MAX_SIZE - 99, 0), 'Sodium' : (MAX_SIZE - 98, 0), 'Magnesium' : (MAX_SIZE - 97, 0), # pylint: disable=E8265 #'Aluminium' : (MAX_SIZE - 96, 0), #'Silicon' : (MAX_SIZE - 95, 0), #'Phosphorus' : (MAX_SIZE - 94, 0), #'Sulfur' : (MAX_SIZE - 93, 0), #'Chlorine' : (MAX_SIZE - 92, 0), #'Argon' : (MAX_SIZE - 91, 0), #'Potassium' : (MAX_SIZE - 90, 0), #'Calcium' : (MAX_SIZE - 89, 0), #'Scandium' : (MAX_SIZE - 88, 0), #'Titanium' : (MAX_SIZE - 87, 0), #'Vanadium' : (MAX_SIZE - 86, 0), #'Chromium' : (MAX_SIZE - 85, 0), #'Manganese' : (MAX_SIZE - 84, 0), #'Iron' : (MAX_SIZE - 83, 0), #'Cobalt' : (MAX_SIZE - 82, 0), #'Nickel' : (MAX_SIZE - 81, 0), #'Copper' : (MAX_SIZE - 80, 0), #'Zinc' : (MAX_SIZE - 79, 0), #'Gallium' : (MAX_SIZE - 78, 0), #'Germanium' : (MAX_SIZE - 77, 0), #'Arsenic' : (MAX_SIZE - 76, 0), #'Selenium' : (MAX_SIZE - 75, 0), #'Bromine' : (MAX_SIZE - 74, 0), #'Krypton' : (MAX_SIZE - 73, 0), #'Rubidium' : (MAX_SIZE - 72, 0), #'Strontium' : (MAX_SIZE - 71, 0), #'Yttrium' : (MAX_SIZE - 70, 0), #'Zirconium' : (MAX_SIZE - 69, 0), #'Niobium' : (MAX_SIZE - 68, 0), #'Molybdenum' : (MAX_SIZE - 67, 0), #'Technetium' : (MAX_SIZE - 66, 0), #'Ruthenium' : (MAX_SIZE - 65, 0), #'Rhodium' : (MAX_SIZE - 64, 0), #'Palladium' : (MAX_SIZE - 63, 0), #'Silver' : (MAX_SIZE - 62, 0), #'Cadmium' : (MAX_SIZE - 61, 0), #'Indium' : (MAX_SIZE - 60, 0), #'Tin' : (MAX_SIZE - 59, 0), #'Antimony' : (MAX_SIZE - 58, 0), #'Tellurium' : (MAX_SIZE - 57, 0), #'Iodine' : (MAX_SIZE - 56, 0), #'Xenon' : (MAX_SIZE - 55, 0), #'Caesium' : (MAX_SIZE - 54, 0), #'Barium' : (MAX_SIZE - 53, 0), #'Lanthanum' : (MAX_SIZE - 52, 0), #'Cerium' : (MAX_SIZE - 51, 0), #'Praseodymium' : (MAX_SIZE - 50, 0), #'Neodymium' : (MAX_SIZE - 49, 0), #'Promethium' : (MAX_SIZE - 48, 0), #'Samarium' : (MAX_SIZE - 47, 0), #'Europium' : (MAX_SIZE - 46, 0), #'Gadolinium' : (MAX_SIZE - 45, 0), #'Terbium' : (MAX_SIZE - 44, 0), #'Dysprosium' : (MAX_SIZE - 43, 0), #'Holmium' : (MAX_SIZE - 42, 0), #'Erbium' : (MAX_SIZE - 41, 0), #'Thulium' : (MAX_SIZE - 40, 0), #'Ytterbium' : (MAX_SIZE - 39, 0), #'Lutetium' : (MAX_SIZE - 38, 0), #'Hafnium' : (MAX_SIZE - 37, 0), #'Tantalum' : (MAX_SIZE - 36, 0), #'Tungsten' : (MAX_SIZE - 35, 0), #'Rhenium' : (MAX_SIZE - 34, 0), #'Osmium' : (MAX_SIZE - 33, 0), #'Iridium' : (MAX_SIZE - 32, 0), #'Platinum' : (MAX_SIZE - 31, 0), #'Gold' : (MAX_SIZE - 30, 0), #'Mercury' : (MAX_SIZE - 29, 0), #'Thallium' : (MAX_SIZE - 28, 0), #'Lead' : (MAX_SIZE - 27, 0), #'Bismuth' : (MAX_SIZE - 26, 0), #'Polonium' : (MAX_SIZE - 25, 0), #'Astatine' : (MAX_SIZE - 24, 0), #'Radon' : (MAX_SIZE - 23, 0), #'Francium' : (MAX_SIZE - 22, 0), #'Radium' : (MAX_SIZE - 21, 0), #'Actinium' : (MAX_SIZE - 20, 0), #'Thorium' : (MAX_SIZE - 19, 0), #'Protactinium' : (MAX_SIZE - 18, 0), #'Uranium' : (MAX_SIZE - 17, 0), #'Neptunium' : (MAX_SIZE - 16, 0), #'Plutonium' : (MAX_SIZE - 15, 0), #'Americium' : (MAX_SIZE - 14, 0), #'Curium' : (MAX_SIZE - 13, 0), #'Berkelium' : (MAX_SIZE - 12, 0), #'Californium' : (MAX_SIZE - 11, 0), #'Einsteinium' : (MAX_SIZE - 10, 0), #'Fermium' : (MAX_SIZE - 9, 0), #'Mendelevium' : (MAX_SIZE - 8, 0), #'Nobelium' : (MAX_SIZE - 7, 0), #'Lawrencium' : (MAX_SIZE - 6, 0), #'Rutherfordium': (MAX_SIZE - 5, 0), #'Dubnium' : (MAX_SIZE - 4, 0), #'Seaborgium' : (MAX_SIZE - 3, 0), #'Bohrium' : (MAX_SIZE - 2, 0), #'Hassium' : (MAX_SIZE - 1, 0), #'Meitnerium' : (MAX_SIZE - 0, 0), # <---- Please refrain from fixing PEP-8 E203 and E265 ------ # pylint: enable=E8203,E8265 } LNAMES = dict((k.lower(), v) for (k, v) in iter(NAMES.items())) VNAMES = dict((v, k) for (k, v) in iter(NAMES.items())) RMATCH = dict((v[:2], k) for (k, v) in iter(NAMES.items())) def __init__(self, # pylint: disable=C0103 major, minor, bugfix=0, mbugfix=0, pre_type=None, pre_num=None, noc=0, sha=None): if isinstance(major, string_types): major = int(major) if isinstance(minor, string_types): minor = int(minor) if bugfix is None: bugfix = 0 elif isinstance(bugfix, string_types): bugfix = int(bugfix) if mbugfix is None: mbugfix = 0 elif isinstance(mbugfix, string_types): mbugfix = int(mbugfix) if pre_type is None: pre_type = '' if pre_num is None: pre_num = 0 elif isinstance(pre_num, string_types): pre_num = int(pre_num) if noc is None: noc = 0 elif isinstance(noc, string_types) and noc == 'n/a': noc = -1 elif isinstance(noc, string_types): noc = int(noc) self.major = major self.minor = minor self.bugfix = bugfix self.mbugfix = mbugfix self.pre_type = pre_type self.pre_num = pre_num self.name = self.VNAMES.get((major, minor), None) self.noc = noc self.sha = sha @classmethod def parse(cls, version_string): if version_string.lower() in cls.LNAMES: return cls.from_name(version_string) vstr = version_string.decode() if isinstance(version_string, bytes) else version_string match = cls.git_describe_regex.match(vstr) if not match: raise ValueError( 'Unable to parse version string: \'{0}\''.format(version_string) ) return cls(*match.groups()) @classmethod def from_name(cls, name): if name.lower() not in cls.LNAMES: raise ValueError( 'Named version \'{0}\' is not known'.format(name) ) return cls(*cls.LNAMES[name.lower()]) @classmethod def from_last_named_version(cls): return cls.from_name( cls.VNAMES[ max([version_info for version_info in cls.VNAMES if version_info[0] < (MAX_SIZE - 200)]) ] ) @classmethod def next_release(cls): return cls.from_name( cls.VNAMES[ min([version_info for version_info in cls.VNAMES if version_info > cls.from_last_named_version().info]) ] ) @property def sse(self): # Higher than 0.17, lower than first date based return 0 < self.major < 2014 @property def info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix ) @property def pre_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num ) @property def noc_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc ) @property def full_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc, self.sha ) @property def string(self): version_string = '{0}.{1}.{2}'.format( self.major, self.minor, self.bugfix ) if self.mbugfix: version_string += '.{0}'.format(self.mbugfix) if self.pre_type: version_string += '{0}{1}'.format(self.pre_type, self.pre_num) if self.noc and self.sha: noc = self.noc if noc < 0: noc = 'n/a' version_string += '-{0}-{1}'.format(noc, self.sha) return version_string @property def formatted_version(self): if self.name and self.major > 10000: version_string = self.name if self.sse: version_string += ' Enterprise' version_string += ' (Unreleased)' return version_string version_string = self.string if self.sse: version_string += ' Enterprise' if (self.major, self.minor) in self.RMATCH: version_string += ' ({0})'.format(self.RMATCH[(self.major, self.minor)]) return version_string def __str__(self): return self.string def __compare__(self, other, method): if not isinstance(other, SaltStackVersion): if isinstance(other, string_types): other = SaltStackVersion.parse(other) elif isinstance(other, (list, tuple)): other = SaltStackVersion(*other) else: raise ValueError( 'Cannot instantiate Version from type \'{0}\''.format( type(other) ) ) if (self.pre_type and other.pre_type) or (not self.pre_type and not other.pre_type): # Both either have or don't have pre-release information, regular compare is ok return method(self.noc_info, other.noc_info) if self.pre_type and not other.pre_type: # We have pre-release information, the other side doesn't other_noc_info = list(other.noc_info) other_noc_info[4] = 'zzzzz' return method(self.noc_info, tuple(other_noc_info)) if not self.pre_type and other.pre_type: # The other side has pre-release informatio, we don't noc_info = list(self.noc_info) noc_info[4] = 'zzzzz' return method(tuple(noc_info), other.noc_info) def __lt__(self, other): return self.__compare__(other, lambda _self, _other: _self < _other) def __le__(self, other): return self.__compare__(other, lambda _self, _other: _self <= _other) def __eq__(self, other): return self.__compare__(other, lambda _self, _other: _self == _other) def __ne__(self, other): return self.__compare__(other, lambda _self, _other: _self != _other) def __ge__(self, other): return self.__compare__(other, lambda _self, _other: _self >= _other) def __gt__(self, other): return self.__compare__(other, lambda _self, _other: _self > _other) def __repr__(self): parts = [] if self.name: parts.append('name=\'{0}\''.format(self.name)) parts.extend([ 'major={0}'.format(self.major), 'minor={0}'.format(self.minor), 'bugfix={0}'.format(self.bugfix) ]) if self.mbugfix: parts.append('minor-bugfix={0}'.format(self.mbugfix)) if self.pre_type: parts.append('{0}={1}'.format(self.pre_type, self.pre_num)) noc = self.noc if noc == -1: noc = 'n/a' if noc and self.sha: parts.extend([ 'noc={0}'.format(noc), 'sha={0}'.format(self.sha) ]) return '<{0} {1}>'.format(self.__class__.__name__, ' '.join(parts)) # ----- Hardcoded Salt Codename Version Information -----------------------------------------------------------------> # # There's no need to do anything here. The last released codename will be picked up # -------------------------------------------------------------------------------------------------------------------- __saltstack_version__ = SaltStackVersion.from_last_named_version() # <---- Hardcoded Salt Version Information --------------------------------------------------------------------------- # ----- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------> def __discover_version(saltstack_version): # This might be a 'python setup.py develop' installation type. Let's # discover the version information at runtime. import os import subprocess if 'SETUP_DIRNAME' in globals(): # This is from the exec() call in Salt's setup.py cwd = SETUP_DIRNAME # pylint: disable=E0602 if not os.path.exists(os.path.join(cwd, '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version else: cwd = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(os.path.join(os.path.dirname(cwd), '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version try: kwargs = dict( stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) if not sys.platform.startswith('win'): # Let's not import `salt.utils` for the above check kwargs['close_fds'] = True process = subprocess.Popen( ['git', 'describe', '--tags', '--first-parent', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if process.returncode != 0: # The git version running this might not support --first-parent # Revert to old command process = subprocess.Popen( ['git', 'describe', '--tags', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if six.PY3: out = out.decode() err = err.decode() out = out.strip() err = err.strip() if not out or err: return saltstack_version try: return SaltStackVersion.parse(out) except ValueError: if not SaltStackVersion.git_sha_regex.match(out): raise # We only define the parsed SHA and set NOC as ??? (unknown) saltstack_version.sha = out.strip() saltstack_version.noc = -1 except OSError as os_err: if os_err.errno != 2: # If the errno is not 2(The system cannot find the file # specified), raise the exception so it can be catch by the # developers raise return saltstack_version def __get_version(saltstack_version): ''' If we can get a version provided at installation time or from Git, use that instead, otherwise we carry on. ''' try: # Try to import the version information provided at install time from salt._version import __saltstack_version__ # pylint: disable=E0611,F0401 return __saltstack_version__ except ImportError: return __discover_version(saltstack_version) # Get additional version information if available __saltstack_version__ = __get_version(__saltstack_version__) # This function has executed once, we're done with it. Delete it! del __get_version # <---- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------- # ----- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------> __version_info__ = __saltstack_version__.info __version__ = __saltstack_version__.string # <---- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------- def salt_information(): ''' Report version of salt. ''' yield 'Salt', __version__ def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return ' '.join(lin_ver) elif mac_ver[0]: if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]): return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]]) else: return ' '.join([mac_ver[0], mac_ver[2]]) elif win_ver[0]: return ' '.join(win_ver) else: return '' if platform.win32_ver()[0]: # Get the version and release info based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof import win32api # pylint: disable=3rd-party-module-not-gated import win32con # pylint: disable=3rd-party-module-not-gated # Get the product name from the registry hkey = win32con.HKEY_LOCAL_MACHINE key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' value_name = 'ProductName' reg_handle = win32api.RegOpenKey(hkey, key) # Returns a tuple of (product_name, value_type) product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name) version = 'Unknown' release = '' if 'Server' in product_name: for item in product_name.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item release = '{0}Server{1}'.format(version, release) else: for item in product_name.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item release = version _, ver, sp, extra = platform.win32_ver() version = ' '.join([release, ver, sp, extra]) else: version = system_version() release = platform.release() system = [ ('system', platform.system()), ('dist', ' '.join(linux_distribution(full_distribution_name=False))), ('release', release), ('machine', platform.machine()), ('version', version), ('locale', __salt_system_encoding__), ] for name, attr in system: yield name, attr continue def versions_information(include_salt_cloud=False): ''' Report the versions of dependent software. ''' salt_info = list(salt_information()) lib_info = list(dependency_information(include_salt_cloud)) sys_info = list(system_information()) return {'Salt Version': dict(salt_info), 'Dependency Versions': dict(lib_info), 'System Versions': dict(sys_info)} def versions_report(include_salt_cloud=False): ''' Yield each version properly formatted for console output. ''' ver_info = versions_information(include_salt_cloud) lib_pad = max(len(name) for name in ver_info['Dependency Versions']) sys_pad = max(len(name) for name in ver_info['System Versions']) padding = max(lib_pad, sys_pad) + 1 fmt = '{0:>{pad}}: {1}' info = [] for ver_type in ('Salt Version', 'Dependency Versions', 'System Versions'): info.append('{0}:'.format(ver_type)) # List dependencies in alphabetical, case insensitive order for name in sorted(ver_info[ver_type], key=lambda x: x.lower()): ver = fmt.format(name, ver_info[ver_type][name] or 'Not Installed', pad=padding) info.append(ver) info.append(' ') for line in info: yield line def msi_conformant_version(): ''' An msi installer uninstalls/replaces a lower "internal version" of itself. "internal version" is ivMAJOR.ivMINOR.ivBUILD with max values 255.255.65535. Using the build nr allows continuous integration of the installer. "Display version" is indipendent and free format: Year.Month.Bugfix as in Salt 2016.11.3. Calculation of the internal version fields: ivMAJOR = 'short year' (2 digits). ivMINOR = 20*(month-1) + Bugfix Combine Month and Bugfix to free ivBUILD for the build number This limits Bugfix < 20. The msi automatically replaces only 19 bugfixes of a month, one must uninstall manually. ivBUILD = git commit count (noc) noc for tags is 0, representing the final word, translates to the highest build number (65535). Examples: git checkout Display version Internal version Remark develop 2016.11.0-742 16.200.742 The develop branch has bugfix 0 2016.11 2016.11.2-78 16.202.78 2016.11 2016.11.9-88 16.209.88 2018.8 2018.3.2-1306 18.42.1306 v2016.11.0 2016.11.0 16.200.65535 Tags have noc 0 v2016.11.2 2016.11.2 16.202.65535 ''' short_year = int(six.text_type(__saltstack_version__.major)[2:]) month = __saltstack_version__.minor bugfix = __saltstack_version__.bugfix if bugfix > 19: bugfix = 19 noc = __saltstack_version__.noc if noc == 0: noc = 65535 return '{}.{}.{}'.format(short_year, 20*(month-1)+bugfix, noc) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'msi': # Building the msi requires an msi-conformant version print(msi_conformant_version()) else: print(__version__)
saltstack/salt
salt/version.py
system_information
python
def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return ' '.join(lin_ver) elif mac_ver[0]: if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]): return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]]) else: return ' '.join([mac_ver[0], mac_ver[2]]) elif win_ver[0]: return ' '.join(win_ver) else: return '' if platform.win32_ver()[0]: # Get the version and release info based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof import win32api # pylint: disable=3rd-party-module-not-gated import win32con # pylint: disable=3rd-party-module-not-gated # Get the product name from the registry hkey = win32con.HKEY_LOCAL_MACHINE key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' value_name = 'ProductName' reg_handle = win32api.RegOpenKey(hkey, key) # Returns a tuple of (product_name, value_type) product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name) version = 'Unknown' release = '' if 'Server' in product_name: for item in product_name.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item release = '{0}Server{1}'.format(version, release) else: for item in product_name.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item release = version _, ver, sp, extra = platform.win32_ver() version = ' '.join([release, ver, sp, extra]) else: version = system_version() release = platform.release() system = [ ('system', platform.system()), ('dist', ' '.join(linux_distribution(full_distribution_name=False))), ('release', release), ('machine', platform.machine()), ('version', version), ('locale', __salt_system_encoding__), ] for name, attr in system: yield name, attr continue
Report system versions.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/version.py#L627-L704
[ "def linux_distribution(**kwargs):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n return _deprecated_linux_distribution(**kwargs)\n", "def system_version():\n '''\n Return host system version.\n '''\n lin_ver = linux_distribution()\n mac_ver = platform.mac_ver()\n win_ver = platform.win32_ver()\n\n if lin_ver[0]:\n return ' '.join(lin_ver)\n elif mac_ver[0]:\n if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]):\n return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]])\n else:\n return ' '.join([mac_ver[0], mac_ver[2]])\n elif win_ver[0]:\n return ' '.join(win_ver)\n else:\n return ''\n" ]
# -*- coding: utf-8 -*- ''' Set up the version of Salt ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import re import sys import platform import warnings # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # pylint: disable=invalid-name,redefined-builtin # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import map # Don't rely on external packages in this module since it's used at install time if sys.version_info[0] == 3: MAX_SIZE = sys.maxsize string_types = (str,) else: MAX_SIZE = sys.maxint string_types = (six.string_types,) # pylint: enable=invalid-name,redefined-builtin # ----- ATTENTION ---------------------------------------------------------------------------------------------------> # # ALL major version bumps, new release codenames, MUST be defined in the SaltStackVersion.NAMES dictionary, i.e.: # # class SaltStackVersion(object): # # NAMES = { # 'Hydrogen': (2014, 1), # <- This is the tuple to bump versions # ( ... ) # } # # # ONLY UPDATE CODENAMES AFTER BRANCHING # # As an example, The Helium codename must only be properly defined with "(2014, 7)" after Hydrogen, "(2014, 1)", has # been branched out into it's own branch. # # ALL OTHER VERSION INFORMATION IS EXTRACTED FROM THE GIT TAGS # # <---- ATTENTION ---------------------------------------------------------------------------------------------------- class SaltStackVersion(object): ''' Handle SaltStack versions class. Knows how to parse ``git describe`` output, knows about release candidates and also supports version comparison. ''' __slots__ = ('name', 'major', 'minor', 'bugfix', 'mbugfix', 'pre_type', 'pre_num', 'noc', 'sha') git_describe_regex = re.compile( r'(?:[^\d]+)?(?P<major>[\d]{1,4})' r'\.(?P<minor>[\d]{1,2})' r'(?:\.(?P<bugfix>[\d]{0,2}))?' r'(?:\.(?P<mbugfix>[\d]{0,2}))?' r'(?:(?P<pre_type>rc|a|b|alpha|beta|nb)(?P<pre_num>[\d]{1}))?' r'(?:(?:.*)-(?P<noc>(?:[\d]+|n/a))-(?P<sha>[a-z0-9]{8}))?' ) git_sha_regex = r'(?P<sha>[a-z0-9]{7})' if six.PY2: git_sha_regex = git_sha_regex.decode(__salt_system_encoding__) git_sha_regex = re.compile(git_sha_regex) # Salt versions after 0.17.0 will be numbered like: # <4-digit-year>.<month>.<bugfix> # # Since the actual version numbers will only be know on release dates, the # periodic table element names will be what's going to be used to name # versions and to be able to mention them. NAMES = { # Let's keep at least 3 version names uncommented counting from the # latest release so we can map deprecation warnings to versions. # pylint: disable=E8203 # ----- Please refrain from fixing PEP-8 E203 and E265 -----> # The idea is to keep this readable. # ----------------------------------------------------------- 'Hydrogen' : (2014, 1), 'Helium' : (2014, 7), 'Lithium' : (2015, 5), 'Beryllium' : (2015, 8), 'Boron' : (2016, 3), 'Carbon' : (2016, 11), 'Nitrogen' : (2017, 7), 'Oxygen' : (2018, 3), 'Fluorine' : (2019, 2), 'Neon' : (MAX_SIZE - 99, 0), 'Sodium' : (MAX_SIZE - 98, 0), 'Magnesium' : (MAX_SIZE - 97, 0), # pylint: disable=E8265 #'Aluminium' : (MAX_SIZE - 96, 0), #'Silicon' : (MAX_SIZE - 95, 0), #'Phosphorus' : (MAX_SIZE - 94, 0), #'Sulfur' : (MAX_SIZE - 93, 0), #'Chlorine' : (MAX_SIZE - 92, 0), #'Argon' : (MAX_SIZE - 91, 0), #'Potassium' : (MAX_SIZE - 90, 0), #'Calcium' : (MAX_SIZE - 89, 0), #'Scandium' : (MAX_SIZE - 88, 0), #'Titanium' : (MAX_SIZE - 87, 0), #'Vanadium' : (MAX_SIZE - 86, 0), #'Chromium' : (MAX_SIZE - 85, 0), #'Manganese' : (MAX_SIZE - 84, 0), #'Iron' : (MAX_SIZE - 83, 0), #'Cobalt' : (MAX_SIZE - 82, 0), #'Nickel' : (MAX_SIZE - 81, 0), #'Copper' : (MAX_SIZE - 80, 0), #'Zinc' : (MAX_SIZE - 79, 0), #'Gallium' : (MAX_SIZE - 78, 0), #'Germanium' : (MAX_SIZE - 77, 0), #'Arsenic' : (MAX_SIZE - 76, 0), #'Selenium' : (MAX_SIZE - 75, 0), #'Bromine' : (MAX_SIZE - 74, 0), #'Krypton' : (MAX_SIZE - 73, 0), #'Rubidium' : (MAX_SIZE - 72, 0), #'Strontium' : (MAX_SIZE - 71, 0), #'Yttrium' : (MAX_SIZE - 70, 0), #'Zirconium' : (MAX_SIZE - 69, 0), #'Niobium' : (MAX_SIZE - 68, 0), #'Molybdenum' : (MAX_SIZE - 67, 0), #'Technetium' : (MAX_SIZE - 66, 0), #'Ruthenium' : (MAX_SIZE - 65, 0), #'Rhodium' : (MAX_SIZE - 64, 0), #'Palladium' : (MAX_SIZE - 63, 0), #'Silver' : (MAX_SIZE - 62, 0), #'Cadmium' : (MAX_SIZE - 61, 0), #'Indium' : (MAX_SIZE - 60, 0), #'Tin' : (MAX_SIZE - 59, 0), #'Antimony' : (MAX_SIZE - 58, 0), #'Tellurium' : (MAX_SIZE - 57, 0), #'Iodine' : (MAX_SIZE - 56, 0), #'Xenon' : (MAX_SIZE - 55, 0), #'Caesium' : (MAX_SIZE - 54, 0), #'Barium' : (MAX_SIZE - 53, 0), #'Lanthanum' : (MAX_SIZE - 52, 0), #'Cerium' : (MAX_SIZE - 51, 0), #'Praseodymium' : (MAX_SIZE - 50, 0), #'Neodymium' : (MAX_SIZE - 49, 0), #'Promethium' : (MAX_SIZE - 48, 0), #'Samarium' : (MAX_SIZE - 47, 0), #'Europium' : (MAX_SIZE - 46, 0), #'Gadolinium' : (MAX_SIZE - 45, 0), #'Terbium' : (MAX_SIZE - 44, 0), #'Dysprosium' : (MAX_SIZE - 43, 0), #'Holmium' : (MAX_SIZE - 42, 0), #'Erbium' : (MAX_SIZE - 41, 0), #'Thulium' : (MAX_SIZE - 40, 0), #'Ytterbium' : (MAX_SIZE - 39, 0), #'Lutetium' : (MAX_SIZE - 38, 0), #'Hafnium' : (MAX_SIZE - 37, 0), #'Tantalum' : (MAX_SIZE - 36, 0), #'Tungsten' : (MAX_SIZE - 35, 0), #'Rhenium' : (MAX_SIZE - 34, 0), #'Osmium' : (MAX_SIZE - 33, 0), #'Iridium' : (MAX_SIZE - 32, 0), #'Platinum' : (MAX_SIZE - 31, 0), #'Gold' : (MAX_SIZE - 30, 0), #'Mercury' : (MAX_SIZE - 29, 0), #'Thallium' : (MAX_SIZE - 28, 0), #'Lead' : (MAX_SIZE - 27, 0), #'Bismuth' : (MAX_SIZE - 26, 0), #'Polonium' : (MAX_SIZE - 25, 0), #'Astatine' : (MAX_SIZE - 24, 0), #'Radon' : (MAX_SIZE - 23, 0), #'Francium' : (MAX_SIZE - 22, 0), #'Radium' : (MAX_SIZE - 21, 0), #'Actinium' : (MAX_SIZE - 20, 0), #'Thorium' : (MAX_SIZE - 19, 0), #'Protactinium' : (MAX_SIZE - 18, 0), #'Uranium' : (MAX_SIZE - 17, 0), #'Neptunium' : (MAX_SIZE - 16, 0), #'Plutonium' : (MAX_SIZE - 15, 0), #'Americium' : (MAX_SIZE - 14, 0), #'Curium' : (MAX_SIZE - 13, 0), #'Berkelium' : (MAX_SIZE - 12, 0), #'Californium' : (MAX_SIZE - 11, 0), #'Einsteinium' : (MAX_SIZE - 10, 0), #'Fermium' : (MAX_SIZE - 9, 0), #'Mendelevium' : (MAX_SIZE - 8, 0), #'Nobelium' : (MAX_SIZE - 7, 0), #'Lawrencium' : (MAX_SIZE - 6, 0), #'Rutherfordium': (MAX_SIZE - 5, 0), #'Dubnium' : (MAX_SIZE - 4, 0), #'Seaborgium' : (MAX_SIZE - 3, 0), #'Bohrium' : (MAX_SIZE - 2, 0), #'Hassium' : (MAX_SIZE - 1, 0), #'Meitnerium' : (MAX_SIZE - 0, 0), # <---- Please refrain from fixing PEP-8 E203 and E265 ------ # pylint: enable=E8203,E8265 } LNAMES = dict((k.lower(), v) for (k, v) in iter(NAMES.items())) VNAMES = dict((v, k) for (k, v) in iter(NAMES.items())) RMATCH = dict((v[:2], k) for (k, v) in iter(NAMES.items())) def __init__(self, # pylint: disable=C0103 major, minor, bugfix=0, mbugfix=0, pre_type=None, pre_num=None, noc=0, sha=None): if isinstance(major, string_types): major = int(major) if isinstance(minor, string_types): minor = int(minor) if bugfix is None: bugfix = 0 elif isinstance(bugfix, string_types): bugfix = int(bugfix) if mbugfix is None: mbugfix = 0 elif isinstance(mbugfix, string_types): mbugfix = int(mbugfix) if pre_type is None: pre_type = '' if pre_num is None: pre_num = 0 elif isinstance(pre_num, string_types): pre_num = int(pre_num) if noc is None: noc = 0 elif isinstance(noc, string_types) and noc == 'n/a': noc = -1 elif isinstance(noc, string_types): noc = int(noc) self.major = major self.minor = minor self.bugfix = bugfix self.mbugfix = mbugfix self.pre_type = pre_type self.pre_num = pre_num self.name = self.VNAMES.get((major, minor), None) self.noc = noc self.sha = sha @classmethod def parse(cls, version_string): if version_string.lower() in cls.LNAMES: return cls.from_name(version_string) vstr = version_string.decode() if isinstance(version_string, bytes) else version_string match = cls.git_describe_regex.match(vstr) if not match: raise ValueError( 'Unable to parse version string: \'{0}\''.format(version_string) ) return cls(*match.groups()) @classmethod def from_name(cls, name): if name.lower() not in cls.LNAMES: raise ValueError( 'Named version \'{0}\' is not known'.format(name) ) return cls(*cls.LNAMES[name.lower()]) @classmethod def from_last_named_version(cls): return cls.from_name( cls.VNAMES[ max([version_info for version_info in cls.VNAMES if version_info[0] < (MAX_SIZE - 200)]) ] ) @classmethod def next_release(cls): return cls.from_name( cls.VNAMES[ min([version_info for version_info in cls.VNAMES if version_info > cls.from_last_named_version().info]) ] ) @property def sse(self): # Higher than 0.17, lower than first date based return 0 < self.major < 2014 @property def info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix ) @property def pre_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num ) @property def noc_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc ) @property def full_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc, self.sha ) @property def string(self): version_string = '{0}.{1}.{2}'.format( self.major, self.minor, self.bugfix ) if self.mbugfix: version_string += '.{0}'.format(self.mbugfix) if self.pre_type: version_string += '{0}{1}'.format(self.pre_type, self.pre_num) if self.noc and self.sha: noc = self.noc if noc < 0: noc = 'n/a' version_string += '-{0}-{1}'.format(noc, self.sha) return version_string @property def formatted_version(self): if self.name and self.major > 10000: version_string = self.name if self.sse: version_string += ' Enterprise' version_string += ' (Unreleased)' return version_string version_string = self.string if self.sse: version_string += ' Enterprise' if (self.major, self.minor) in self.RMATCH: version_string += ' ({0})'.format(self.RMATCH[(self.major, self.minor)]) return version_string def __str__(self): return self.string def __compare__(self, other, method): if not isinstance(other, SaltStackVersion): if isinstance(other, string_types): other = SaltStackVersion.parse(other) elif isinstance(other, (list, tuple)): other = SaltStackVersion(*other) else: raise ValueError( 'Cannot instantiate Version from type \'{0}\''.format( type(other) ) ) if (self.pre_type and other.pre_type) or (not self.pre_type and not other.pre_type): # Both either have or don't have pre-release information, regular compare is ok return method(self.noc_info, other.noc_info) if self.pre_type and not other.pre_type: # We have pre-release information, the other side doesn't other_noc_info = list(other.noc_info) other_noc_info[4] = 'zzzzz' return method(self.noc_info, tuple(other_noc_info)) if not self.pre_type and other.pre_type: # The other side has pre-release informatio, we don't noc_info = list(self.noc_info) noc_info[4] = 'zzzzz' return method(tuple(noc_info), other.noc_info) def __lt__(self, other): return self.__compare__(other, lambda _self, _other: _self < _other) def __le__(self, other): return self.__compare__(other, lambda _self, _other: _self <= _other) def __eq__(self, other): return self.__compare__(other, lambda _self, _other: _self == _other) def __ne__(self, other): return self.__compare__(other, lambda _self, _other: _self != _other) def __ge__(self, other): return self.__compare__(other, lambda _self, _other: _self >= _other) def __gt__(self, other): return self.__compare__(other, lambda _self, _other: _self > _other) def __repr__(self): parts = [] if self.name: parts.append('name=\'{0}\''.format(self.name)) parts.extend([ 'major={0}'.format(self.major), 'minor={0}'.format(self.minor), 'bugfix={0}'.format(self.bugfix) ]) if self.mbugfix: parts.append('minor-bugfix={0}'.format(self.mbugfix)) if self.pre_type: parts.append('{0}={1}'.format(self.pre_type, self.pre_num)) noc = self.noc if noc == -1: noc = 'n/a' if noc and self.sha: parts.extend([ 'noc={0}'.format(noc), 'sha={0}'.format(self.sha) ]) return '<{0} {1}>'.format(self.__class__.__name__, ' '.join(parts)) # ----- Hardcoded Salt Codename Version Information -----------------------------------------------------------------> # # There's no need to do anything here. The last released codename will be picked up # -------------------------------------------------------------------------------------------------------------------- __saltstack_version__ = SaltStackVersion.from_last_named_version() # <---- Hardcoded Salt Version Information --------------------------------------------------------------------------- # ----- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------> def __discover_version(saltstack_version): # This might be a 'python setup.py develop' installation type. Let's # discover the version information at runtime. import os import subprocess if 'SETUP_DIRNAME' in globals(): # This is from the exec() call in Salt's setup.py cwd = SETUP_DIRNAME # pylint: disable=E0602 if not os.path.exists(os.path.join(cwd, '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version else: cwd = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(os.path.join(os.path.dirname(cwd), '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version try: kwargs = dict( stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) if not sys.platform.startswith('win'): # Let's not import `salt.utils` for the above check kwargs['close_fds'] = True process = subprocess.Popen( ['git', 'describe', '--tags', '--first-parent', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if process.returncode != 0: # The git version running this might not support --first-parent # Revert to old command process = subprocess.Popen( ['git', 'describe', '--tags', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if six.PY3: out = out.decode() err = err.decode() out = out.strip() err = err.strip() if not out or err: return saltstack_version try: return SaltStackVersion.parse(out) except ValueError: if not SaltStackVersion.git_sha_regex.match(out): raise # We only define the parsed SHA and set NOC as ??? (unknown) saltstack_version.sha = out.strip() saltstack_version.noc = -1 except OSError as os_err: if os_err.errno != 2: # If the errno is not 2(The system cannot find the file # specified), raise the exception so it can be catch by the # developers raise return saltstack_version def __get_version(saltstack_version): ''' If we can get a version provided at installation time or from Git, use that instead, otherwise we carry on. ''' try: # Try to import the version information provided at install time from salt._version import __saltstack_version__ # pylint: disable=E0611,F0401 return __saltstack_version__ except ImportError: return __discover_version(saltstack_version) # Get additional version information if available __saltstack_version__ = __get_version(__saltstack_version__) # This function has executed once, we're done with it. Delete it! del __get_version # <---- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------- # ----- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------> __version_info__ = __saltstack_version__.info __version__ = __saltstack_version__.string # <---- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------- def salt_information(): ''' Report version of salt. ''' yield 'Salt', __version__ def dependency_information(include_salt_cloud=False): ''' Report versions of library dependencies. ''' libs = [ ('Python', None, sys.version.rsplit('\n')[0].strip()), ('Jinja2', 'jinja2', '__version__'), ('M2Crypto', 'M2Crypto', 'version'), ('msgpack-python', 'msgpack', 'version'), ('msgpack-pure', 'msgpack_pure', 'version'), ('pycrypto', 'Crypto', '__version__'), ('pycryptodome', 'Cryptodome', 'version_info'), ('PyYAML', 'yaml', '__version__'), ('PyZMQ', 'zmq', '__version__'), ('ZMQ', 'zmq', 'zmq_version'), ('Mako', 'mako', '__version__'), ('Tornado', 'tornado', 'version'), ('timelib', 'timelib', 'version'), ('dateutil', 'dateutil', '__version__'), ('pygit2', 'pygit2', '__version__'), ('libgit2', 'pygit2', 'LIBGIT2_VERSION'), ('smmap', 'smmap', '__version__'), ('cffi', 'cffi', '__version__'), ('pycparser', 'pycparser', '__version__'), ('gitdb', 'gitdb', '__version__'), ('gitpython', 'git', '__version__'), ('python-gnupg', 'gnupg', '__version__'), ('mysql-python', 'MySQLdb', '__version__'), ('cherrypy', 'cherrypy', '__version__'), ('docker-py', 'docker', '__version__'), ] if include_salt_cloud: libs.append( ('Apache Libcloud', 'libcloud', '__version__'), ) for name, imp, attr in libs: if imp is None: yield name, attr continue try: imp = __import__(imp) version = getattr(imp, attr) if callable(version): version = version() if isinstance(version, (tuple, list)): version = '.'.join(map(str, version)) yield name, version except Exception: yield name, None def versions_information(include_salt_cloud=False): ''' Report the versions of dependent software. ''' salt_info = list(salt_information()) lib_info = list(dependency_information(include_salt_cloud)) sys_info = list(system_information()) return {'Salt Version': dict(salt_info), 'Dependency Versions': dict(lib_info), 'System Versions': dict(sys_info)} def versions_report(include_salt_cloud=False): ''' Yield each version properly formatted for console output. ''' ver_info = versions_information(include_salt_cloud) lib_pad = max(len(name) for name in ver_info['Dependency Versions']) sys_pad = max(len(name) for name in ver_info['System Versions']) padding = max(lib_pad, sys_pad) + 1 fmt = '{0:>{pad}}: {1}' info = [] for ver_type in ('Salt Version', 'Dependency Versions', 'System Versions'): info.append('{0}:'.format(ver_type)) # List dependencies in alphabetical, case insensitive order for name in sorted(ver_info[ver_type], key=lambda x: x.lower()): ver = fmt.format(name, ver_info[ver_type][name] or 'Not Installed', pad=padding) info.append(ver) info.append(' ') for line in info: yield line def msi_conformant_version(): ''' An msi installer uninstalls/replaces a lower "internal version" of itself. "internal version" is ivMAJOR.ivMINOR.ivBUILD with max values 255.255.65535. Using the build nr allows continuous integration of the installer. "Display version" is indipendent and free format: Year.Month.Bugfix as in Salt 2016.11.3. Calculation of the internal version fields: ivMAJOR = 'short year' (2 digits). ivMINOR = 20*(month-1) + Bugfix Combine Month and Bugfix to free ivBUILD for the build number This limits Bugfix < 20. The msi automatically replaces only 19 bugfixes of a month, one must uninstall manually. ivBUILD = git commit count (noc) noc for tags is 0, representing the final word, translates to the highest build number (65535). Examples: git checkout Display version Internal version Remark develop 2016.11.0-742 16.200.742 The develop branch has bugfix 0 2016.11 2016.11.2-78 16.202.78 2016.11 2016.11.9-88 16.209.88 2018.8 2018.3.2-1306 18.42.1306 v2016.11.0 2016.11.0 16.200.65535 Tags have noc 0 v2016.11.2 2016.11.2 16.202.65535 ''' short_year = int(six.text_type(__saltstack_version__.major)[2:]) month = __saltstack_version__.minor bugfix = __saltstack_version__.bugfix if bugfix > 19: bugfix = 19 noc = __saltstack_version__.noc if noc == 0: noc = 65535 return '{}.{}.{}'.format(short_year, 20*(month-1)+bugfix, noc) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'msi': # Building the msi requires an msi-conformant version print(msi_conformant_version()) else: print(__version__)
saltstack/salt
salt/version.py
versions_information
python
def versions_information(include_salt_cloud=False): ''' Report the versions of dependent software. ''' salt_info = list(salt_information()) lib_info = list(dependency_information(include_salt_cloud)) sys_info = list(system_information()) return {'Salt Version': dict(salt_info), 'Dependency Versions': dict(lib_info), 'System Versions': dict(sys_info)}
Report the versions of dependent software.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/version.py#L707-L717
[ "def system_information():\n '''\n Report system versions.\n '''\n def system_version():\n '''\n Return host system version.\n '''\n lin_ver = linux_distribution()\n mac_ver = platform.mac_ver()\n win_ver = platform.win32_ver()\n\n if lin_ver[0]:\n return ' '.join(lin_ver)\n elif mac_ver[0]:\n if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]):\n return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]])\n else:\n return ' '.join([mac_ver[0], mac_ver[2]])\n elif win_ver[0]:\n return ' '.join(win_ver)\n else:\n return ''\n\n if platform.win32_ver()[0]:\n # Get the version and release info based on the Windows Operating\n # System Product Name. As long as Microsoft maintains a similar format\n # this should be future proof\n import win32api # pylint: disable=3rd-party-module-not-gated\n import win32con # pylint: disable=3rd-party-module-not-gated\n\n # Get the product name from the registry\n hkey = win32con.HKEY_LOCAL_MACHINE\n key = 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion'\n value_name = 'ProductName'\n reg_handle = win32api.RegOpenKey(hkey, key)\n\n # Returns a tuple of (product_name, value_type)\n product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name)\n\n version = 'Unknown'\n release = ''\n if 'Server' in product_name:\n for item in product_name.split(' '):\n # If it's all digits, then it's version\n if re.match(r'\\d+', item):\n version = item\n # If it starts with R and then numbers, it's the release\n # ie: R2\n if re.match(r'^R\\d+$', item):\n release = item\n release = '{0}Server{1}'.format(version, release)\n else:\n for item in product_name.split(' '):\n # If it's a number, decimal number, Thin or Vista, then it's the\n # version\n if re.match(r'^(\\d+(\\.\\d+)?)|Thin|Vista$', item):\n version = item\n release = version\n\n _, ver, sp, extra = platform.win32_ver()\n version = ' '.join([release, ver, sp, extra])\n else:\n version = system_version()\n release = platform.release()\n\n system = [\n ('system', platform.system()),\n ('dist', ' '.join(linux_distribution(full_distribution_name=False))),\n ('release', release),\n ('machine', platform.machine()),\n ('version', version),\n ('locale', __salt_system_encoding__),\n ]\n\n for name, attr in system:\n yield name, attr\n continue\n", "def salt_information():\n '''\n Report version of salt.\n '''\n yield 'Salt', __version__\n", "def dependency_information(include_salt_cloud=False):\n '''\n Report versions of library dependencies.\n '''\n libs = [\n ('Python', None, sys.version.rsplit('\\n')[0].strip()),\n ('Jinja2', 'jinja2', '__version__'),\n ('M2Crypto', 'M2Crypto', 'version'),\n ('msgpack-python', 'msgpack', 'version'),\n ('msgpack-pure', 'msgpack_pure', 'version'),\n ('pycrypto', 'Crypto', '__version__'),\n ('pycryptodome', 'Cryptodome', 'version_info'),\n ('PyYAML', 'yaml', '__version__'),\n ('PyZMQ', 'zmq', '__version__'),\n ('ZMQ', 'zmq', 'zmq_version'),\n ('Mako', 'mako', '__version__'),\n ('Tornado', 'tornado', 'version'),\n ('timelib', 'timelib', 'version'),\n ('dateutil', 'dateutil', '__version__'),\n ('pygit2', 'pygit2', '__version__'),\n ('libgit2', 'pygit2', 'LIBGIT2_VERSION'),\n ('smmap', 'smmap', '__version__'),\n ('cffi', 'cffi', '__version__'),\n ('pycparser', 'pycparser', '__version__'),\n ('gitdb', 'gitdb', '__version__'),\n ('gitpython', 'git', '__version__'),\n ('python-gnupg', 'gnupg', '__version__'),\n ('mysql-python', 'MySQLdb', '__version__'),\n ('cherrypy', 'cherrypy', '__version__'),\n ('docker-py', 'docker', '__version__'),\n ]\n\n if include_salt_cloud:\n libs.append(\n ('Apache Libcloud', 'libcloud', '__version__'),\n )\n\n for name, imp, attr in libs:\n if imp is None:\n yield name, attr\n continue\n try:\n imp = __import__(imp)\n version = getattr(imp, attr)\n if callable(version):\n version = version()\n if isinstance(version, (tuple, list)):\n version = '.'.join(map(str, version))\n yield name, version\n except Exception:\n yield name, None\n" ]
# -*- coding: utf-8 -*- ''' Set up the version of Salt ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import re import sys import platform import warnings # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # pylint: disable=invalid-name,redefined-builtin # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import map # Don't rely on external packages in this module since it's used at install time if sys.version_info[0] == 3: MAX_SIZE = sys.maxsize string_types = (str,) else: MAX_SIZE = sys.maxint string_types = (six.string_types,) # pylint: enable=invalid-name,redefined-builtin # ----- ATTENTION ---------------------------------------------------------------------------------------------------> # # ALL major version bumps, new release codenames, MUST be defined in the SaltStackVersion.NAMES dictionary, i.e.: # # class SaltStackVersion(object): # # NAMES = { # 'Hydrogen': (2014, 1), # <- This is the tuple to bump versions # ( ... ) # } # # # ONLY UPDATE CODENAMES AFTER BRANCHING # # As an example, The Helium codename must only be properly defined with "(2014, 7)" after Hydrogen, "(2014, 1)", has # been branched out into it's own branch. # # ALL OTHER VERSION INFORMATION IS EXTRACTED FROM THE GIT TAGS # # <---- ATTENTION ---------------------------------------------------------------------------------------------------- class SaltStackVersion(object): ''' Handle SaltStack versions class. Knows how to parse ``git describe`` output, knows about release candidates and also supports version comparison. ''' __slots__ = ('name', 'major', 'minor', 'bugfix', 'mbugfix', 'pre_type', 'pre_num', 'noc', 'sha') git_describe_regex = re.compile( r'(?:[^\d]+)?(?P<major>[\d]{1,4})' r'\.(?P<minor>[\d]{1,2})' r'(?:\.(?P<bugfix>[\d]{0,2}))?' r'(?:\.(?P<mbugfix>[\d]{0,2}))?' r'(?:(?P<pre_type>rc|a|b|alpha|beta|nb)(?P<pre_num>[\d]{1}))?' r'(?:(?:.*)-(?P<noc>(?:[\d]+|n/a))-(?P<sha>[a-z0-9]{8}))?' ) git_sha_regex = r'(?P<sha>[a-z0-9]{7})' if six.PY2: git_sha_regex = git_sha_regex.decode(__salt_system_encoding__) git_sha_regex = re.compile(git_sha_regex) # Salt versions after 0.17.0 will be numbered like: # <4-digit-year>.<month>.<bugfix> # # Since the actual version numbers will only be know on release dates, the # periodic table element names will be what's going to be used to name # versions and to be able to mention them. NAMES = { # Let's keep at least 3 version names uncommented counting from the # latest release so we can map deprecation warnings to versions. # pylint: disable=E8203 # ----- Please refrain from fixing PEP-8 E203 and E265 -----> # The idea is to keep this readable. # ----------------------------------------------------------- 'Hydrogen' : (2014, 1), 'Helium' : (2014, 7), 'Lithium' : (2015, 5), 'Beryllium' : (2015, 8), 'Boron' : (2016, 3), 'Carbon' : (2016, 11), 'Nitrogen' : (2017, 7), 'Oxygen' : (2018, 3), 'Fluorine' : (2019, 2), 'Neon' : (MAX_SIZE - 99, 0), 'Sodium' : (MAX_SIZE - 98, 0), 'Magnesium' : (MAX_SIZE - 97, 0), # pylint: disable=E8265 #'Aluminium' : (MAX_SIZE - 96, 0), #'Silicon' : (MAX_SIZE - 95, 0), #'Phosphorus' : (MAX_SIZE - 94, 0), #'Sulfur' : (MAX_SIZE - 93, 0), #'Chlorine' : (MAX_SIZE - 92, 0), #'Argon' : (MAX_SIZE - 91, 0), #'Potassium' : (MAX_SIZE - 90, 0), #'Calcium' : (MAX_SIZE - 89, 0), #'Scandium' : (MAX_SIZE - 88, 0), #'Titanium' : (MAX_SIZE - 87, 0), #'Vanadium' : (MAX_SIZE - 86, 0), #'Chromium' : (MAX_SIZE - 85, 0), #'Manganese' : (MAX_SIZE - 84, 0), #'Iron' : (MAX_SIZE - 83, 0), #'Cobalt' : (MAX_SIZE - 82, 0), #'Nickel' : (MAX_SIZE - 81, 0), #'Copper' : (MAX_SIZE - 80, 0), #'Zinc' : (MAX_SIZE - 79, 0), #'Gallium' : (MAX_SIZE - 78, 0), #'Germanium' : (MAX_SIZE - 77, 0), #'Arsenic' : (MAX_SIZE - 76, 0), #'Selenium' : (MAX_SIZE - 75, 0), #'Bromine' : (MAX_SIZE - 74, 0), #'Krypton' : (MAX_SIZE - 73, 0), #'Rubidium' : (MAX_SIZE - 72, 0), #'Strontium' : (MAX_SIZE - 71, 0), #'Yttrium' : (MAX_SIZE - 70, 0), #'Zirconium' : (MAX_SIZE - 69, 0), #'Niobium' : (MAX_SIZE - 68, 0), #'Molybdenum' : (MAX_SIZE - 67, 0), #'Technetium' : (MAX_SIZE - 66, 0), #'Ruthenium' : (MAX_SIZE - 65, 0), #'Rhodium' : (MAX_SIZE - 64, 0), #'Palladium' : (MAX_SIZE - 63, 0), #'Silver' : (MAX_SIZE - 62, 0), #'Cadmium' : (MAX_SIZE - 61, 0), #'Indium' : (MAX_SIZE - 60, 0), #'Tin' : (MAX_SIZE - 59, 0), #'Antimony' : (MAX_SIZE - 58, 0), #'Tellurium' : (MAX_SIZE - 57, 0), #'Iodine' : (MAX_SIZE - 56, 0), #'Xenon' : (MAX_SIZE - 55, 0), #'Caesium' : (MAX_SIZE - 54, 0), #'Barium' : (MAX_SIZE - 53, 0), #'Lanthanum' : (MAX_SIZE - 52, 0), #'Cerium' : (MAX_SIZE - 51, 0), #'Praseodymium' : (MAX_SIZE - 50, 0), #'Neodymium' : (MAX_SIZE - 49, 0), #'Promethium' : (MAX_SIZE - 48, 0), #'Samarium' : (MAX_SIZE - 47, 0), #'Europium' : (MAX_SIZE - 46, 0), #'Gadolinium' : (MAX_SIZE - 45, 0), #'Terbium' : (MAX_SIZE - 44, 0), #'Dysprosium' : (MAX_SIZE - 43, 0), #'Holmium' : (MAX_SIZE - 42, 0), #'Erbium' : (MAX_SIZE - 41, 0), #'Thulium' : (MAX_SIZE - 40, 0), #'Ytterbium' : (MAX_SIZE - 39, 0), #'Lutetium' : (MAX_SIZE - 38, 0), #'Hafnium' : (MAX_SIZE - 37, 0), #'Tantalum' : (MAX_SIZE - 36, 0), #'Tungsten' : (MAX_SIZE - 35, 0), #'Rhenium' : (MAX_SIZE - 34, 0), #'Osmium' : (MAX_SIZE - 33, 0), #'Iridium' : (MAX_SIZE - 32, 0), #'Platinum' : (MAX_SIZE - 31, 0), #'Gold' : (MAX_SIZE - 30, 0), #'Mercury' : (MAX_SIZE - 29, 0), #'Thallium' : (MAX_SIZE - 28, 0), #'Lead' : (MAX_SIZE - 27, 0), #'Bismuth' : (MAX_SIZE - 26, 0), #'Polonium' : (MAX_SIZE - 25, 0), #'Astatine' : (MAX_SIZE - 24, 0), #'Radon' : (MAX_SIZE - 23, 0), #'Francium' : (MAX_SIZE - 22, 0), #'Radium' : (MAX_SIZE - 21, 0), #'Actinium' : (MAX_SIZE - 20, 0), #'Thorium' : (MAX_SIZE - 19, 0), #'Protactinium' : (MAX_SIZE - 18, 0), #'Uranium' : (MAX_SIZE - 17, 0), #'Neptunium' : (MAX_SIZE - 16, 0), #'Plutonium' : (MAX_SIZE - 15, 0), #'Americium' : (MAX_SIZE - 14, 0), #'Curium' : (MAX_SIZE - 13, 0), #'Berkelium' : (MAX_SIZE - 12, 0), #'Californium' : (MAX_SIZE - 11, 0), #'Einsteinium' : (MAX_SIZE - 10, 0), #'Fermium' : (MAX_SIZE - 9, 0), #'Mendelevium' : (MAX_SIZE - 8, 0), #'Nobelium' : (MAX_SIZE - 7, 0), #'Lawrencium' : (MAX_SIZE - 6, 0), #'Rutherfordium': (MAX_SIZE - 5, 0), #'Dubnium' : (MAX_SIZE - 4, 0), #'Seaborgium' : (MAX_SIZE - 3, 0), #'Bohrium' : (MAX_SIZE - 2, 0), #'Hassium' : (MAX_SIZE - 1, 0), #'Meitnerium' : (MAX_SIZE - 0, 0), # <---- Please refrain from fixing PEP-8 E203 and E265 ------ # pylint: enable=E8203,E8265 } LNAMES = dict((k.lower(), v) for (k, v) in iter(NAMES.items())) VNAMES = dict((v, k) for (k, v) in iter(NAMES.items())) RMATCH = dict((v[:2], k) for (k, v) in iter(NAMES.items())) def __init__(self, # pylint: disable=C0103 major, minor, bugfix=0, mbugfix=0, pre_type=None, pre_num=None, noc=0, sha=None): if isinstance(major, string_types): major = int(major) if isinstance(minor, string_types): minor = int(minor) if bugfix is None: bugfix = 0 elif isinstance(bugfix, string_types): bugfix = int(bugfix) if mbugfix is None: mbugfix = 0 elif isinstance(mbugfix, string_types): mbugfix = int(mbugfix) if pre_type is None: pre_type = '' if pre_num is None: pre_num = 0 elif isinstance(pre_num, string_types): pre_num = int(pre_num) if noc is None: noc = 0 elif isinstance(noc, string_types) and noc == 'n/a': noc = -1 elif isinstance(noc, string_types): noc = int(noc) self.major = major self.minor = minor self.bugfix = bugfix self.mbugfix = mbugfix self.pre_type = pre_type self.pre_num = pre_num self.name = self.VNAMES.get((major, minor), None) self.noc = noc self.sha = sha @classmethod def parse(cls, version_string): if version_string.lower() in cls.LNAMES: return cls.from_name(version_string) vstr = version_string.decode() if isinstance(version_string, bytes) else version_string match = cls.git_describe_regex.match(vstr) if not match: raise ValueError( 'Unable to parse version string: \'{0}\''.format(version_string) ) return cls(*match.groups()) @classmethod def from_name(cls, name): if name.lower() not in cls.LNAMES: raise ValueError( 'Named version \'{0}\' is not known'.format(name) ) return cls(*cls.LNAMES[name.lower()]) @classmethod def from_last_named_version(cls): return cls.from_name( cls.VNAMES[ max([version_info for version_info in cls.VNAMES if version_info[0] < (MAX_SIZE - 200)]) ] ) @classmethod def next_release(cls): return cls.from_name( cls.VNAMES[ min([version_info for version_info in cls.VNAMES if version_info > cls.from_last_named_version().info]) ] ) @property def sse(self): # Higher than 0.17, lower than first date based return 0 < self.major < 2014 @property def info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix ) @property def pre_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num ) @property def noc_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc ) @property def full_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc, self.sha ) @property def string(self): version_string = '{0}.{1}.{2}'.format( self.major, self.minor, self.bugfix ) if self.mbugfix: version_string += '.{0}'.format(self.mbugfix) if self.pre_type: version_string += '{0}{1}'.format(self.pre_type, self.pre_num) if self.noc and self.sha: noc = self.noc if noc < 0: noc = 'n/a' version_string += '-{0}-{1}'.format(noc, self.sha) return version_string @property def formatted_version(self): if self.name and self.major > 10000: version_string = self.name if self.sse: version_string += ' Enterprise' version_string += ' (Unreleased)' return version_string version_string = self.string if self.sse: version_string += ' Enterprise' if (self.major, self.minor) in self.RMATCH: version_string += ' ({0})'.format(self.RMATCH[(self.major, self.minor)]) return version_string def __str__(self): return self.string def __compare__(self, other, method): if not isinstance(other, SaltStackVersion): if isinstance(other, string_types): other = SaltStackVersion.parse(other) elif isinstance(other, (list, tuple)): other = SaltStackVersion(*other) else: raise ValueError( 'Cannot instantiate Version from type \'{0}\''.format( type(other) ) ) if (self.pre_type and other.pre_type) or (not self.pre_type and not other.pre_type): # Both either have or don't have pre-release information, regular compare is ok return method(self.noc_info, other.noc_info) if self.pre_type and not other.pre_type: # We have pre-release information, the other side doesn't other_noc_info = list(other.noc_info) other_noc_info[4] = 'zzzzz' return method(self.noc_info, tuple(other_noc_info)) if not self.pre_type and other.pre_type: # The other side has pre-release informatio, we don't noc_info = list(self.noc_info) noc_info[4] = 'zzzzz' return method(tuple(noc_info), other.noc_info) def __lt__(self, other): return self.__compare__(other, lambda _self, _other: _self < _other) def __le__(self, other): return self.__compare__(other, lambda _self, _other: _self <= _other) def __eq__(self, other): return self.__compare__(other, lambda _self, _other: _self == _other) def __ne__(self, other): return self.__compare__(other, lambda _self, _other: _self != _other) def __ge__(self, other): return self.__compare__(other, lambda _self, _other: _self >= _other) def __gt__(self, other): return self.__compare__(other, lambda _self, _other: _self > _other) def __repr__(self): parts = [] if self.name: parts.append('name=\'{0}\''.format(self.name)) parts.extend([ 'major={0}'.format(self.major), 'minor={0}'.format(self.minor), 'bugfix={0}'.format(self.bugfix) ]) if self.mbugfix: parts.append('minor-bugfix={0}'.format(self.mbugfix)) if self.pre_type: parts.append('{0}={1}'.format(self.pre_type, self.pre_num)) noc = self.noc if noc == -1: noc = 'n/a' if noc and self.sha: parts.extend([ 'noc={0}'.format(noc), 'sha={0}'.format(self.sha) ]) return '<{0} {1}>'.format(self.__class__.__name__, ' '.join(parts)) # ----- Hardcoded Salt Codename Version Information -----------------------------------------------------------------> # # There's no need to do anything here. The last released codename will be picked up # -------------------------------------------------------------------------------------------------------------------- __saltstack_version__ = SaltStackVersion.from_last_named_version() # <---- Hardcoded Salt Version Information --------------------------------------------------------------------------- # ----- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------> def __discover_version(saltstack_version): # This might be a 'python setup.py develop' installation type. Let's # discover the version information at runtime. import os import subprocess if 'SETUP_DIRNAME' in globals(): # This is from the exec() call in Salt's setup.py cwd = SETUP_DIRNAME # pylint: disable=E0602 if not os.path.exists(os.path.join(cwd, '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version else: cwd = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(os.path.join(os.path.dirname(cwd), '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version try: kwargs = dict( stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) if not sys.platform.startswith('win'): # Let's not import `salt.utils` for the above check kwargs['close_fds'] = True process = subprocess.Popen( ['git', 'describe', '--tags', '--first-parent', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if process.returncode != 0: # The git version running this might not support --first-parent # Revert to old command process = subprocess.Popen( ['git', 'describe', '--tags', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if six.PY3: out = out.decode() err = err.decode() out = out.strip() err = err.strip() if not out or err: return saltstack_version try: return SaltStackVersion.parse(out) except ValueError: if not SaltStackVersion.git_sha_regex.match(out): raise # We only define the parsed SHA and set NOC as ??? (unknown) saltstack_version.sha = out.strip() saltstack_version.noc = -1 except OSError as os_err: if os_err.errno != 2: # If the errno is not 2(The system cannot find the file # specified), raise the exception so it can be catch by the # developers raise return saltstack_version def __get_version(saltstack_version): ''' If we can get a version provided at installation time or from Git, use that instead, otherwise we carry on. ''' try: # Try to import the version information provided at install time from salt._version import __saltstack_version__ # pylint: disable=E0611,F0401 return __saltstack_version__ except ImportError: return __discover_version(saltstack_version) # Get additional version information if available __saltstack_version__ = __get_version(__saltstack_version__) # This function has executed once, we're done with it. Delete it! del __get_version # <---- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------- # ----- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------> __version_info__ = __saltstack_version__.info __version__ = __saltstack_version__.string # <---- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------- def salt_information(): ''' Report version of salt. ''' yield 'Salt', __version__ def dependency_information(include_salt_cloud=False): ''' Report versions of library dependencies. ''' libs = [ ('Python', None, sys.version.rsplit('\n')[0].strip()), ('Jinja2', 'jinja2', '__version__'), ('M2Crypto', 'M2Crypto', 'version'), ('msgpack-python', 'msgpack', 'version'), ('msgpack-pure', 'msgpack_pure', 'version'), ('pycrypto', 'Crypto', '__version__'), ('pycryptodome', 'Cryptodome', 'version_info'), ('PyYAML', 'yaml', '__version__'), ('PyZMQ', 'zmq', '__version__'), ('ZMQ', 'zmq', 'zmq_version'), ('Mako', 'mako', '__version__'), ('Tornado', 'tornado', 'version'), ('timelib', 'timelib', 'version'), ('dateutil', 'dateutil', '__version__'), ('pygit2', 'pygit2', '__version__'), ('libgit2', 'pygit2', 'LIBGIT2_VERSION'), ('smmap', 'smmap', '__version__'), ('cffi', 'cffi', '__version__'), ('pycparser', 'pycparser', '__version__'), ('gitdb', 'gitdb', '__version__'), ('gitpython', 'git', '__version__'), ('python-gnupg', 'gnupg', '__version__'), ('mysql-python', 'MySQLdb', '__version__'), ('cherrypy', 'cherrypy', '__version__'), ('docker-py', 'docker', '__version__'), ] if include_salt_cloud: libs.append( ('Apache Libcloud', 'libcloud', '__version__'), ) for name, imp, attr in libs: if imp is None: yield name, attr continue try: imp = __import__(imp) version = getattr(imp, attr) if callable(version): version = version() if isinstance(version, (tuple, list)): version = '.'.join(map(str, version)) yield name, version except Exception: yield name, None def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return ' '.join(lin_ver) elif mac_ver[0]: if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]): return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]]) else: return ' '.join([mac_ver[0], mac_ver[2]]) elif win_ver[0]: return ' '.join(win_ver) else: return '' if platform.win32_ver()[0]: # Get the version and release info based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof import win32api # pylint: disable=3rd-party-module-not-gated import win32con # pylint: disable=3rd-party-module-not-gated # Get the product name from the registry hkey = win32con.HKEY_LOCAL_MACHINE key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' value_name = 'ProductName' reg_handle = win32api.RegOpenKey(hkey, key) # Returns a tuple of (product_name, value_type) product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name) version = 'Unknown' release = '' if 'Server' in product_name: for item in product_name.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item release = '{0}Server{1}'.format(version, release) else: for item in product_name.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item release = version _, ver, sp, extra = platform.win32_ver() version = ' '.join([release, ver, sp, extra]) else: version = system_version() release = platform.release() system = [ ('system', platform.system()), ('dist', ' '.join(linux_distribution(full_distribution_name=False))), ('release', release), ('machine', platform.machine()), ('version', version), ('locale', __salt_system_encoding__), ] for name, attr in system: yield name, attr continue def versions_report(include_salt_cloud=False): ''' Yield each version properly formatted for console output. ''' ver_info = versions_information(include_salt_cloud) lib_pad = max(len(name) for name in ver_info['Dependency Versions']) sys_pad = max(len(name) for name in ver_info['System Versions']) padding = max(lib_pad, sys_pad) + 1 fmt = '{0:>{pad}}: {1}' info = [] for ver_type in ('Salt Version', 'Dependency Versions', 'System Versions'): info.append('{0}:'.format(ver_type)) # List dependencies in alphabetical, case insensitive order for name in sorted(ver_info[ver_type], key=lambda x: x.lower()): ver = fmt.format(name, ver_info[ver_type][name] or 'Not Installed', pad=padding) info.append(ver) info.append(' ') for line in info: yield line def msi_conformant_version(): ''' An msi installer uninstalls/replaces a lower "internal version" of itself. "internal version" is ivMAJOR.ivMINOR.ivBUILD with max values 255.255.65535. Using the build nr allows continuous integration of the installer. "Display version" is indipendent and free format: Year.Month.Bugfix as in Salt 2016.11.3. Calculation of the internal version fields: ivMAJOR = 'short year' (2 digits). ivMINOR = 20*(month-1) + Bugfix Combine Month and Bugfix to free ivBUILD for the build number This limits Bugfix < 20. The msi automatically replaces only 19 bugfixes of a month, one must uninstall manually. ivBUILD = git commit count (noc) noc for tags is 0, representing the final word, translates to the highest build number (65535). Examples: git checkout Display version Internal version Remark develop 2016.11.0-742 16.200.742 The develop branch has bugfix 0 2016.11 2016.11.2-78 16.202.78 2016.11 2016.11.9-88 16.209.88 2018.8 2018.3.2-1306 18.42.1306 v2016.11.0 2016.11.0 16.200.65535 Tags have noc 0 v2016.11.2 2016.11.2 16.202.65535 ''' short_year = int(six.text_type(__saltstack_version__.major)[2:]) month = __saltstack_version__.minor bugfix = __saltstack_version__.bugfix if bugfix > 19: bugfix = 19 noc = __saltstack_version__.noc if noc == 0: noc = 65535 return '{}.{}.{}'.format(short_year, 20*(month-1)+bugfix, noc) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'msi': # Building the msi requires an msi-conformant version print(msi_conformant_version()) else: print(__version__)
saltstack/salt
salt/version.py
versions_report
python
def versions_report(include_salt_cloud=False): ''' Yield each version properly formatted for console output. ''' ver_info = versions_information(include_salt_cloud) lib_pad = max(len(name) for name in ver_info['Dependency Versions']) sys_pad = max(len(name) for name in ver_info['System Versions']) padding = max(lib_pad, sys_pad) + 1 fmt = '{0:>{pad}}: {1}' info = [] for ver_type in ('Salt Version', 'Dependency Versions', 'System Versions'): info.append('{0}:'.format(ver_type)) # List dependencies in alphabetical, case insensitive order for name in sorted(ver_info[ver_type], key=lambda x: x.lower()): ver = fmt.format(name, ver_info[ver_type][name] or 'Not Installed', pad=padding) info.append(ver) info.append(' ') for line in info: yield line
Yield each version properly formatted for console output.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/version.py#L720-L743
[ "def versions_information(include_salt_cloud=False):\n '''\n Report the versions of dependent software.\n '''\n salt_info = list(salt_information())\n lib_info = list(dependency_information(include_salt_cloud))\n sys_info = list(system_information())\n\n return {'Salt Version': dict(salt_info),\n 'Dependency Versions': dict(lib_info),\n 'System Versions': dict(sys_info)}\n" ]
# -*- coding: utf-8 -*- ''' Set up the version of Salt ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import re import sys import platform import warnings # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # pylint: disable=invalid-name,redefined-builtin # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import map # Don't rely on external packages in this module since it's used at install time if sys.version_info[0] == 3: MAX_SIZE = sys.maxsize string_types = (str,) else: MAX_SIZE = sys.maxint string_types = (six.string_types,) # pylint: enable=invalid-name,redefined-builtin # ----- ATTENTION ---------------------------------------------------------------------------------------------------> # # ALL major version bumps, new release codenames, MUST be defined in the SaltStackVersion.NAMES dictionary, i.e.: # # class SaltStackVersion(object): # # NAMES = { # 'Hydrogen': (2014, 1), # <- This is the tuple to bump versions # ( ... ) # } # # # ONLY UPDATE CODENAMES AFTER BRANCHING # # As an example, The Helium codename must only be properly defined with "(2014, 7)" after Hydrogen, "(2014, 1)", has # been branched out into it's own branch. # # ALL OTHER VERSION INFORMATION IS EXTRACTED FROM THE GIT TAGS # # <---- ATTENTION ---------------------------------------------------------------------------------------------------- class SaltStackVersion(object): ''' Handle SaltStack versions class. Knows how to parse ``git describe`` output, knows about release candidates and also supports version comparison. ''' __slots__ = ('name', 'major', 'minor', 'bugfix', 'mbugfix', 'pre_type', 'pre_num', 'noc', 'sha') git_describe_regex = re.compile( r'(?:[^\d]+)?(?P<major>[\d]{1,4})' r'\.(?P<minor>[\d]{1,2})' r'(?:\.(?P<bugfix>[\d]{0,2}))?' r'(?:\.(?P<mbugfix>[\d]{0,2}))?' r'(?:(?P<pre_type>rc|a|b|alpha|beta|nb)(?P<pre_num>[\d]{1}))?' r'(?:(?:.*)-(?P<noc>(?:[\d]+|n/a))-(?P<sha>[a-z0-9]{8}))?' ) git_sha_regex = r'(?P<sha>[a-z0-9]{7})' if six.PY2: git_sha_regex = git_sha_regex.decode(__salt_system_encoding__) git_sha_regex = re.compile(git_sha_regex) # Salt versions after 0.17.0 will be numbered like: # <4-digit-year>.<month>.<bugfix> # # Since the actual version numbers will only be know on release dates, the # periodic table element names will be what's going to be used to name # versions and to be able to mention them. NAMES = { # Let's keep at least 3 version names uncommented counting from the # latest release so we can map deprecation warnings to versions. # pylint: disable=E8203 # ----- Please refrain from fixing PEP-8 E203 and E265 -----> # The idea is to keep this readable. # ----------------------------------------------------------- 'Hydrogen' : (2014, 1), 'Helium' : (2014, 7), 'Lithium' : (2015, 5), 'Beryllium' : (2015, 8), 'Boron' : (2016, 3), 'Carbon' : (2016, 11), 'Nitrogen' : (2017, 7), 'Oxygen' : (2018, 3), 'Fluorine' : (2019, 2), 'Neon' : (MAX_SIZE - 99, 0), 'Sodium' : (MAX_SIZE - 98, 0), 'Magnesium' : (MAX_SIZE - 97, 0), # pylint: disable=E8265 #'Aluminium' : (MAX_SIZE - 96, 0), #'Silicon' : (MAX_SIZE - 95, 0), #'Phosphorus' : (MAX_SIZE - 94, 0), #'Sulfur' : (MAX_SIZE - 93, 0), #'Chlorine' : (MAX_SIZE - 92, 0), #'Argon' : (MAX_SIZE - 91, 0), #'Potassium' : (MAX_SIZE - 90, 0), #'Calcium' : (MAX_SIZE - 89, 0), #'Scandium' : (MAX_SIZE - 88, 0), #'Titanium' : (MAX_SIZE - 87, 0), #'Vanadium' : (MAX_SIZE - 86, 0), #'Chromium' : (MAX_SIZE - 85, 0), #'Manganese' : (MAX_SIZE - 84, 0), #'Iron' : (MAX_SIZE - 83, 0), #'Cobalt' : (MAX_SIZE - 82, 0), #'Nickel' : (MAX_SIZE - 81, 0), #'Copper' : (MAX_SIZE - 80, 0), #'Zinc' : (MAX_SIZE - 79, 0), #'Gallium' : (MAX_SIZE - 78, 0), #'Germanium' : (MAX_SIZE - 77, 0), #'Arsenic' : (MAX_SIZE - 76, 0), #'Selenium' : (MAX_SIZE - 75, 0), #'Bromine' : (MAX_SIZE - 74, 0), #'Krypton' : (MAX_SIZE - 73, 0), #'Rubidium' : (MAX_SIZE - 72, 0), #'Strontium' : (MAX_SIZE - 71, 0), #'Yttrium' : (MAX_SIZE - 70, 0), #'Zirconium' : (MAX_SIZE - 69, 0), #'Niobium' : (MAX_SIZE - 68, 0), #'Molybdenum' : (MAX_SIZE - 67, 0), #'Technetium' : (MAX_SIZE - 66, 0), #'Ruthenium' : (MAX_SIZE - 65, 0), #'Rhodium' : (MAX_SIZE - 64, 0), #'Palladium' : (MAX_SIZE - 63, 0), #'Silver' : (MAX_SIZE - 62, 0), #'Cadmium' : (MAX_SIZE - 61, 0), #'Indium' : (MAX_SIZE - 60, 0), #'Tin' : (MAX_SIZE - 59, 0), #'Antimony' : (MAX_SIZE - 58, 0), #'Tellurium' : (MAX_SIZE - 57, 0), #'Iodine' : (MAX_SIZE - 56, 0), #'Xenon' : (MAX_SIZE - 55, 0), #'Caesium' : (MAX_SIZE - 54, 0), #'Barium' : (MAX_SIZE - 53, 0), #'Lanthanum' : (MAX_SIZE - 52, 0), #'Cerium' : (MAX_SIZE - 51, 0), #'Praseodymium' : (MAX_SIZE - 50, 0), #'Neodymium' : (MAX_SIZE - 49, 0), #'Promethium' : (MAX_SIZE - 48, 0), #'Samarium' : (MAX_SIZE - 47, 0), #'Europium' : (MAX_SIZE - 46, 0), #'Gadolinium' : (MAX_SIZE - 45, 0), #'Terbium' : (MAX_SIZE - 44, 0), #'Dysprosium' : (MAX_SIZE - 43, 0), #'Holmium' : (MAX_SIZE - 42, 0), #'Erbium' : (MAX_SIZE - 41, 0), #'Thulium' : (MAX_SIZE - 40, 0), #'Ytterbium' : (MAX_SIZE - 39, 0), #'Lutetium' : (MAX_SIZE - 38, 0), #'Hafnium' : (MAX_SIZE - 37, 0), #'Tantalum' : (MAX_SIZE - 36, 0), #'Tungsten' : (MAX_SIZE - 35, 0), #'Rhenium' : (MAX_SIZE - 34, 0), #'Osmium' : (MAX_SIZE - 33, 0), #'Iridium' : (MAX_SIZE - 32, 0), #'Platinum' : (MAX_SIZE - 31, 0), #'Gold' : (MAX_SIZE - 30, 0), #'Mercury' : (MAX_SIZE - 29, 0), #'Thallium' : (MAX_SIZE - 28, 0), #'Lead' : (MAX_SIZE - 27, 0), #'Bismuth' : (MAX_SIZE - 26, 0), #'Polonium' : (MAX_SIZE - 25, 0), #'Astatine' : (MAX_SIZE - 24, 0), #'Radon' : (MAX_SIZE - 23, 0), #'Francium' : (MAX_SIZE - 22, 0), #'Radium' : (MAX_SIZE - 21, 0), #'Actinium' : (MAX_SIZE - 20, 0), #'Thorium' : (MAX_SIZE - 19, 0), #'Protactinium' : (MAX_SIZE - 18, 0), #'Uranium' : (MAX_SIZE - 17, 0), #'Neptunium' : (MAX_SIZE - 16, 0), #'Plutonium' : (MAX_SIZE - 15, 0), #'Americium' : (MAX_SIZE - 14, 0), #'Curium' : (MAX_SIZE - 13, 0), #'Berkelium' : (MAX_SIZE - 12, 0), #'Californium' : (MAX_SIZE - 11, 0), #'Einsteinium' : (MAX_SIZE - 10, 0), #'Fermium' : (MAX_SIZE - 9, 0), #'Mendelevium' : (MAX_SIZE - 8, 0), #'Nobelium' : (MAX_SIZE - 7, 0), #'Lawrencium' : (MAX_SIZE - 6, 0), #'Rutherfordium': (MAX_SIZE - 5, 0), #'Dubnium' : (MAX_SIZE - 4, 0), #'Seaborgium' : (MAX_SIZE - 3, 0), #'Bohrium' : (MAX_SIZE - 2, 0), #'Hassium' : (MAX_SIZE - 1, 0), #'Meitnerium' : (MAX_SIZE - 0, 0), # <---- Please refrain from fixing PEP-8 E203 and E265 ------ # pylint: enable=E8203,E8265 } LNAMES = dict((k.lower(), v) for (k, v) in iter(NAMES.items())) VNAMES = dict((v, k) for (k, v) in iter(NAMES.items())) RMATCH = dict((v[:2], k) for (k, v) in iter(NAMES.items())) def __init__(self, # pylint: disable=C0103 major, minor, bugfix=0, mbugfix=0, pre_type=None, pre_num=None, noc=0, sha=None): if isinstance(major, string_types): major = int(major) if isinstance(minor, string_types): minor = int(minor) if bugfix is None: bugfix = 0 elif isinstance(bugfix, string_types): bugfix = int(bugfix) if mbugfix is None: mbugfix = 0 elif isinstance(mbugfix, string_types): mbugfix = int(mbugfix) if pre_type is None: pre_type = '' if pre_num is None: pre_num = 0 elif isinstance(pre_num, string_types): pre_num = int(pre_num) if noc is None: noc = 0 elif isinstance(noc, string_types) and noc == 'n/a': noc = -1 elif isinstance(noc, string_types): noc = int(noc) self.major = major self.minor = minor self.bugfix = bugfix self.mbugfix = mbugfix self.pre_type = pre_type self.pre_num = pre_num self.name = self.VNAMES.get((major, minor), None) self.noc = noc self.sha = sha @classmethod def parse(cls, version_string): if version_string.lower() in cls.LNAMES: return cls.from_name(version_string) vstr = version_string.decode() if isinstance(version_string, bytes) else version_string match = cls.git_describe_regex.match(vstr) if not match: raise ValueError( 'Unable to parse version string: \'{0}\''.format(version_string) ) return cls(*match.groups()) @classmethod def from_name(cls, name): if name.lower() not in cls.LNAMES: raise ValueError( 'Named version \'{0}\' is not known'.format(name) ) return cls(*cls.LNAMES[name.lower()]) @classmethod def from_last_named_version(cls): return cls.from_name( cls.VNAMES[ max([version_info for version_info in cls.VNAMES if version_info[0] < (MAX_SIZE - 200)]) ] ) @classmethod def next_release(cls): return cls.from_name( cls.VNAMES[ min([version_info for version_info in cls.VNAMES if version_info > cls.from_last_named_version().info]) ] ) @property def sse(self): # Higher than 0.17, lower than first date based return 0 < self.major < 2014 @property def info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix ) @property def pre_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num ) @property def noc_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc ) @property def full_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc, self.sha ) @property def string(self): version_string = '{0}.{1}.{2}'.format( self.major, self.minor, self.bugfix ) if self.mbugfix: version_string += '.{0}'.format(self.mbugfix) if self.pre_type: version_string += '{0}{1}'.format(self.pre_type, self.pre_num) if self.noc and self.sha: noc = self.noc if noc < 0: noc = 'n/a' version_string += '-{0}-{1}'.format(noc, self.sha) return version_string @property def formatted_version(self): if self.name and self.major > 10000: version_string = self.name if self.sse: version_string += ' Enterprise' version_string += ' (Unreleased)' return version_string version_string = self.string if self.sse: version_string += ' Enterprise' if (self.major, self.minor) in self.RMATCH: version_string += ' ({0})'.format(self.RMATCH[(self.major, self.minor)]) return version_string def __str__(self): return self.string def __compare__(self, other, method): if not isinstance(other, SaltStackVersion): if isinstance(other, string_types): other = SaltStackVersion.parse(other) elif isinstance(other, (list, tuple)): other = SaltStackVersion(*other) else: raise ValueError( 'Cannot instantiate Version from type \'{0}\''.format( type(other) ) ) if (self.pre_type and other.pre_type) or (not self.pre_type and not other.pre_type): # Both either have or don't have pre-release information, regular compare is ok return method(self.noc_info, other.noc_info) if self.pre_type and not other.pre_type: # We have pre-release information, the other side doesn't other_noc_info = list(other.noc_info) other_noc_info[4] = 'zzzzz' return method(self.noc_info, tuple(other_noc_info)) if not self.pre_type and other.pre_type: # The other side has pre-release informatio, we don't noc_info = list(self.noc_info) noc_info[4] = 'zzzzz' return method(tuple(noc_info), other.noc_info) def __lt__(self, other): return self.__compare__(other, lambda _self, _other: _self < _other) def __le__(self, other): return self.__compare__(other, lambda _self, _other: _self <= _other) def __eq__(self, other): return self.__compare__(other, lambda _self, _other: _self == _other) def __ne__(self, other): return self.__compare__(other, lambda _self, _other: _self != _other) def __ge__(self, other): return self.__compare__(other, lambda _self, _other: _self >= _other) def __gt__(self, other): return self.__compare__(other, lambda _self, _other: _self > _other) def __repr__(self): parts = [] if self.name: parts.append('name=\'{0}\''.format(self.name)) parts.extend([ 'major={0}'.format(self.major), 'minor={0}'.format(self.minor), 'bugfix={0}'.format(self.bugfix) ]) if self.mbugfix: parts.append('minor-bugfix={0}'.format(self.mbugfix)) if self.pre_type: parts.append('{0}={1}'.format(self.pre_type, self.pre_num)) noc = self.noc if noc == -1: noc = 'n/a' if noc and self.sha: parts.extend([ 'noc={0}'.format(noc), 'sha={0}'.format(self.sha) ]) return '<{0} {1}>'.format(self.__class__.__name__, ' '.join(parts)) # ----- Hardcoded Salt Codename Version Information -----------------------------------------------------------------> # # There's no need to do anything here. The last released codename will be picked up # -------------------------------------------------------------------------------------------------------------------- __saltstack_version__ = SaltStackVersion.from_last_named_version() # <---- Hardcoded Salt Version Information --------------------------------------------------------------------------- # ----- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------> def __discover_version(saltstack_version): # This might be a 'python setup.py develop' installation type. Let's # discover the version information at runtime. import os import subprocess if 'SETUP_DIRNAME' in globals(): # This is from the exec() call in Salt's setup.py cwd = SETUP_DIRNAME # pylint: disable=E0602 if not os.path.exists(os.path.join(cwd, '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version else: cwd = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(os.path.join(os.path.dirname(cwd), '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version try: kwargs = dict( stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) if not sys.platform.startswith('win'): # Let's not import `salt.utils` for the above check kwargs['close_fds'] = True process = subprocess.Popen( ['git', 'describe', '--tags', '--first-parent', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if process.returncode != 0: # The git version running this might not support --first-parent # Revert to old command process = subprocess.Popen( ['git', 'describe', '--tags', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if six.PY3: out = out.decode() err = err.decode() out = out.strip() err = err.strip() if not out or err: return saltstack_version try: return SaltStackVersion.parse(out) except ValueError: if not SaltStackVersion.git_sha_regex.match(out): raise # We only define the parsed SHA and set NOC as ??? (unknown) saltstack_version.sha = out.strip() saltstack_version.noc = -1 except OSError as os_err: if os_err.errno != 2: # If the errno is not 2(The system cannot find the file # specified), raise the exception so it can be catch by the # developers raise return saltstack_version def __get_version(saltstack_version): ''' If we can get a version provided at installation time or from Git, use that instead, otherwise we carry on. ''' try: # Try to import the version information provided at install time from salt._version import __saltstack_version__ # pylint: disable=E0611,F0401 return __saltstack_version__ except ImportError: return __discover_version(saltstack_version) # Get additional version information if available __saltstack_version__ = __get_version(__saltstack_version__) # This function has executed once, we're done with it. Delete it! del __get_version # <---- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------- # ----- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------> __version_info__ = __saltstack_version__.info __version__ = __saltstack_version__.string # <---- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------- def salt_information(): ''' Report version of salt. ''' yield 'Salt', __version__ def dependency_information(include_salt_cloud=False): ''' Report versions of library dependencies. ''' libs = [ ('Python', None, sys.version.rsplit('\n')[0].strip()), ('Jinja2', 'jinja2', '__version__'), ('M2Crypto', 'M2Crypto', 'version'), ('msgpack-python', 'msgpack', 'version'), ('msgpack-pure', 'msgpack_pure', 'version'), ('pycrypto', 'Crypto', '__version__'), ('pycryptodome', 'Cryptodome', 'version_info'), ('PyYAML', 'yaml', '__version__'), ('PyZMQ', 'zmq', '__version__'), ('ZMQ', 'zmq', 'zmq_version'), ('Mako', 'mako', '__version__'), ('Tornado', 'tornado', 'version'), ('timelib', 'timelib', 'version'), ('dateutil', 'dateutil', '__version__'), ('pygit2', 'pygit2', '__version__'), ('libgit2', 'pygit2', 'LIBGIT2_VERSION'), ('smmap', 'smmap', '__version__'), ('cffi', 'cffi', '__version__'), ('pycparser', 'pycparser', '__version__'), ('gitdb', 'gitdb', '__version__'), ('gitpython', 'git', '__version__'), ('python-gnupg', 'gnupg', '__version__'), ('mysql-python', 'MySQLdb', '__version__'), ('cherrypy', 'cherrypy', '__version__'), ('docker-py', 'docker', '__version__'), ] if include_salt_cloud: libs.append( ('Apache Libcloud', 'libcloud', '__version__'), ) for name, imp, attr in libs: if imp is None: yield name, attr continue try: imp = __import__(imp) version = getattr(imp, attr) if callable(version): version = version() if isinstance(version, (tuple, list)): version = '.'.join(map(str, version)) yield name, version except Exception: yield name, None def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return ' '.join(lin_ver) elif mac_ver[0]: if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]): return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]]) else: return ' '.join([mac_ver[0], mac_ver[2]]) elif win_ver[0]: return ' '.join(win_ver) else: return '' if platform.win32_ver()[0]: # Get the version and release info based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof import win32api # pylint: disable=3rd-party-module-not-gated import win32con # pylint: disable=3rd-party-module-not-gated # Get the product name from the registry hkey = win32con.HKEY_LOCAL_MACHINE key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' value_name = 'ProductName' reg_handle = win32api.RegOpenKey(hkey, key) # Returns a tuple of (product_name, value_type) product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name) version = 'Unknown' release = '' if 'Server' in product_name: for item in product_name.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item release = '{0}Server{1}'.format(version, release) else: for item in product_name.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item release = version _, ver, sp, extra = platform.win32_ver() version = ' '.join([release, ver, sp, extra]) else: version = system_version() release = platform.release() system = [ ('system', platform.system()), ('dist', ' '.join(linux_distribution(full_distribution_name=False))), ('release', release), ('machine', platform.machine()), ('version', version), ('locale', __salt_system_encoding__), ] for name, attr in system: yield name, attr continue def versions_information(include_salt_cloud=False): ''' Report the versions of dependent software. ''' salt_info = list(salt_information()) lib_info = list(dependency_information(include_salt_cloud)) sys_info = list(system_information()) return {'Salt Version': dict(salt_info), 'Dependency Versions': dict(lib_info), 'System Versions': dict(sys_info)} def msi_conformant_version(): ''' An msi installer uninstalls/replaces a lower "internal version" of itself. "internal version" is ivMAJOR.ivMINOR.ivBUILD with max values 255.255.65535. Using the build nr allows continuous integration of the installer. "Display version" is indipendent and free format: Year.Month.Bugfix as in Salt 2016.11.3. Calculation of the internal version fields: ivMAJOR = 'short year' (2 digits). ivMINOR = 20*(month-1) + Bugfix Combine Month and Bugfix to free ivBUILD for the build number This limits Bugfix < 20. The msi automatically replaces only 19 bugfixes of a month, one must uninstall manually. ivBUILD = git commit count (noc) noc for tags is 0, representing the final word, translates to the highest build number (65535). Examples: git checkout Display version Internal version Remark develop 2016.11.0-742 16.200.742 The develop branch has bugfix 0 2016.11 2016.11.2-78 16.202.78 2016.11 2016.11.9-88 16.209.88 2018.8 2018.3.2-1306 18.42.1306 v2016.11.0 2016.11.0 16.200.65535 Tags have noc 0 v2016.11.2 2016.11.2 16.202.65535 ''' short_year = int(six.text_type(__saltstack_version__.major)[2:]) month = __saltstack_version__.minor bugfix = __saltstack_version__.bugfix if bugfix > 19: bugfix = 19 noc = __saltstack_version__.noc if noc == 0: noc = 65535 return '{}.{}.{}'.format(short_year, 20*(month-1)+bugfix, noc) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'msi': # Building the msi requires an msi-conformant version print(msi_conformant_version()) else: print(__version__)
saltstack/salt
salt/version.py
msi_conformant_version
python
def msi_conformant_version(): ''' An msi installer uninstalls/replaces a lower "internal version" of itself. "internal version" is ivMAJOR.ivMINOR.ivBUILD with max values 255.255.65535. Using the build nr allows continuous integration of the installer. "Display version" is indipendent and free format: Year.Month.Bugfix as in Salt 2016.11.3. Calculation of the internal version fields: ivMAJOR = 'short year' (2 digits). ivMINOR = 20*(month-1) + Bugfix Combine Month and Bugfix to free ivBUILD for the build number This limits Bugfix < 20. The msi automatically replaces only 19 bugfixes of a month, one must uninstall manually. ivBUILD = git commit count (noc) noc for tags is 0, representing the final word, translates to the highest build number (65535). Examples: git checkout Display version Internal version Remark develop 2016.11.0-742 16.200.742 The develop branch has bugfix 0 2016.11 2016.11.2-78 16.202.78 2016.11 2016.11.9-88 16.209.88 2018.8 2018.3.2-1306 18.42.1306 v2016.11.0 2016.11.0 16.200.65535 Tags have noc 0 v2016.11.2 2016.11.2 16.202.65535 ''' short_year = int(six.text_type(__saltstack_version__.major)[2:]) month = __saltstack_version__.minor bugfix = __saltstack_version__.bugfix if bugfix > 19: bugfix = 19 noc = __saltstack_version__.noc if noc == 0: noc = 65535 return '{}.{}.{}'.format(short_year, 20*(month-1)+bugfix, noc)
An msi installer uninstalls/replaces a lower "internal version" of itself. "internal version" is ivMAJOR.ivMINOR.ivBUILD with max values 255.255.65535. Using the build nr allows continuous integration of the installer. "Display version" is indipendent and free format: Year.Month.Bugfix as in Salt 2016.11.3. Calculation of the internal version fields: ivMAJOR = 'short year' (2 digits). ivMINOR = 20*(month-1) + Bugfix Combine Month and Bugfix to free ivBUILD for the build number This limits Bugfix < 20. The msi automatically replaces only 19 bugfixes of a month, one must uninstall manually. ivBUILD = git commit count (noc) noc for tags is 0, representing the final word, translates to the highest build number (65535). Examples: git checkout Display version Internal version Remark develop 2016.11.0-742 16.200.742 The develop branch has bugfix 0 2016.11 2016.11.2-78 16.202.78 2016.11 2016.11.9-88 16.209.88 2018.8 2018.3.2-1306 18.42.1306 v2016.11.0 2016.11.0 16.200.65535 Tags have noc 0 v2016.11.2 2016.11.2 16.202.65535
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/version.py#L746-L779
null
# -*- coding: utf-8 -*- ''' Set up the version of Salt ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import re import sys import platform import warnings # linux_distribution deprecated in py3.7 try: from platform import linux_distribution as _deprecated_linux_distribution def linux_distribution(**kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") return _deprecated_linux_distribution(**kwargs) except ImportError: from distro import linux_distribution # pylint: disable=invalid-name,redefined-builtin # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import map # Don't rely on external packages in this module since it's used at install time if sys.version_info[0] == 3: MAX_SIZE = sys.maxsize string_types = (str,) else: MAX_SIZE = sys.maxint string_types = (six.string_types,) # pylint: enable=invalid-name,redefined-builtin # ----- ATTENTION ---------------------------------------------------------------------------------------------------> # # ALL major version bumps, new release codenames, MUST be defined in the SaltStackVersion.NAMES dictionary, i.e.: # # class SaltStackVersion(object): # # NAMES = { # 'Hydrogen': (2014, 1), # <- This is the tuple to bump versions # ( ... ) # } # # # ONLY UPDATE CODENAMES AFTER BRANCHING # # As an example, The Helium codename must only be properly defined with "(2014, 7)" after Hydrogen, "(2014, 1)", has # been branched out into it's own branch. # # ALL OTHER VERSION INFORMATION IS EXTRACTED FROM THE GIT TAGS # # <---- ATTENTION ---------------------------------------------------------------------------------------------------- class SaltStackVersion(object): ''' Handle SaltStack versions class. Knows how to parse ``git describe`` output, knows about release candidates and also supports version comparison. ''' __slots__ = ('name', 'major', 'minor', 'bugfix', 'mbugfix', 'pre_type', 'pre_num', 'noc', 'sha') git_describe_regex = re.compile( r'(?:[^\d]+)?(?P<major>[\d]{1,4})' r'\.(?P<minor>[\d]{1,2})' r'(?:\.(?P<bugfix>[\d]{0,2}))?' r'(?:\.(?P<mbugfix>[\d]{0,2}))?' r'(?:(?P<pre_type>rc|a|b|alpha|beta|nb)(?P<pre_num>[\d]{1}))?' r'(?:(?:.*)-(?P<noc>(?:[\d]+|n/a))-(?P<sha>[a-z0-9]{8}))?' ) git_sha_regex = r'(?P<sha>[a-z0-9]{7})' if six.PY2: git_sha_regex = git_sha_regex.decode(__salt_system_encoding__) git_sha_regex = re.compile(git_sha_regex) # Salt versions after 0.17.0 will be numbered like: # <4-digit-year>.<month>.<bugfix> # # Since the actual version numbers will only be know on release dates, the # periodic table element names will be what's going to be used to name # versions and to be able to mention them. NAMES = { # Let's keep at least 3 version names uncommented counting from the # latest release so we can map deprecation warnings to versions. # pylint: disable=E8203 # ----- Please refrain from fixing PEP-8 E203 and E265 -----> # The idea is to keep this readable. # ----------------------------------------------------------- 'Hydrogen' : (2014, 1), 'Helium' : (2014, 7), 'Lithium' : (2015, 5), 'Beryllium' : (2015, 8), 'Boron' : (2016, 3), 'Carbon' : (2016, 11), 'Nitrogen' : (2017, 7), 'Oxygen' : (2018, 3), 'Fluorine' : (2019, 2), 'Neon' : (MAX_SIZE - 99, 0), 'Sodium' : (MAX_SIZE - 98, 0), 'Magnesium' : (MAX_SIZE - 97, 0), # pylint: disable=E8265 #'Aluminium' : (MAX_SIZE - 96, 0), #'Silicon' : (MAX_SIZE - 95, 0), #'Phosphorus' : (MAX_SIZE - 94, 0), #'Sulfur' : (MAX_SIZE - 93, 0), #'Chlorine' : (MAX_SIZE - 92, 0), #'Argon' : (MAX_SIZE - 91, 0), #'Potassium' : (MAX_SIZE - 90, 0), #'Calcium' : (MAX_SIZE - 89, 0), #'Scandium' : (MAX_SIZE - 88, 0), #'Titanium' : (MAX_SIZE - 87, 0), #'Vanadium' : (MAX_SIZE - 86, 0), #'Chromium' : (MAX_SIZE - 85, 0), #'Manganese' : (MAX_SIZE - 84, 0), #'Iron' : (MAX_SIZE - 83, 0), #'Cobalt' : (MAX_SIZE - 82, 0), #'Nickel' : (MAX_SIZE - 81, 0), #'Copper' : (MAX_SIZE - 80, 0), #'Zinc' : (MAX_SIZE - 79, 0), #'Gallium' : (MAX_SIZE - 78, 0), #'Germanium' : (MAX_SIZE - 77, 0), #'Arsenic' : (MAX_SIZE - 76, 0), #'Selenium' : (MAX_SIZE - 75, 0), #'Bromine' : (MAX_SIZE - 74, 0), #'Krypton' : (MAX_SIZE - 73, 0), #'Rubidium' : (MAX_SIZE - 72, 0), #'Strontium' : (MAX_SIZE - 71, 0), #'Yttrium' : (MAX_SIZE - 70, 0), #'Zirconium' : (MAX_SIZE - 69, 0), #'Niobium' : (MAX_SIZE - 68, 0), #'Molybdenum' : (MAX_SIZE - 67, 0), #'Technetium' : (MAX_SIZE - 66, 0), #'Ruthenium' : (MAX_SIZE - 65, 0), #'Rhodium' : (MAX_SIZE - 64, 0), #'Palladium' : (MAX_SIZE - 63, 0), #'Silver' : (MAX_SIZE - 62, 0), #'Cadmium' : (MAX_SIZE - 61, 0), #'Indium' : (MAX_SIZE - 60, 0), #'Tin' : (MAX_SIZE - 59, 0), #'Antimony' : (MAX_SIZE - 58, 0), #'Tellurium' : (MAX_SIZE - 57, 0), #'Iodine' : (MAX_SIZE - 56, 0), #'Xenon' : (MAX_SIZE - 55, 0), #'Caesium' : (MAX_SIZE - 54, 0), #'Barium' : (MAX_SIZE - 53, 0), #'Lanthanum' : (MAX_SIZE - 52, 0), #'Cerium' : (MAX_SIZE - 51, 0), #'Praseodymium' : (MAX_SIZE - 50, 0), #'Neodymium' : (MAX_SIZE - 49, 0), #'Promethium' : (MAX_SIZE - 48, 0), #'Samarium' : (MAX_SIZE - 47, 0), #'Europium' : (MAX_SIZE - 46, 0), #'Gadolinium' : (MAX_SIZE - 45, 0), #'Terbium' : (MAX_SIZE - 44, 0), #'Dysprosium' : (MAX_SIZE - 43, 0), #'Holmium' : (MAX_SIZE - 42, 0), #'Erbium' : (MAX_SIZE - 41, 0), #'Thulium' : (MAX_SIZE - 40, 0), #'Ytterbium' : (MAX_SIZE - 39, 0), #'Lutetium' : (MAX_SIZE - 38, 0), #'Hafnium' : (MAX_SIZE - 37, 0), #'Tantalum' : (MAX_SIZE - 36, 0), #'Tungsten' : (MAX_SIZE - 35, 0), #'Rhenium' : (MAX_SIZE - 34, 0), #'Osmium' : (MAX_SIZE - 33, 0), #'Iridium' : (MAX_SIZE - 32, 0), #'Platinum' : (MAX_SIZE - 31, 0), #'Gold' : (MAX_SIZE - 30, 0), #'Mercury' : (MAX_SIZE - 29, 0), #'Thallium' : (MAX_SIZE - 28, 0), #'Lead' : (MAX_SIZE - 27, 0), #'Bismuth' : (MAX_SIZE - 26, 0), #'Polonium' : (MAX_SIZE - 25, 0), #'Astatine' : (MAX_SIZE - 24, 0), #'Radon' : (MAX_SIZE - 23, 0), #'Francium' : (MAX_SIZE - 22, 0), #'Radium' : (MAX_SIZE - 21, 0), #'Actinium' : (MAX_SIZE - 20, 0), #'Thorium' : (MAX_SIZE - 19, 0), #'Protactinium' : (MAX_SIZE - 18, 0), #'Uranium' : (MAX_SIZE - 17, 0), #'Neptunium' : (MAX_SIZE - 16, 0), #'Plutonium' : (MAX_SIZE - 15, 0), #'Americium' : (MAX_SIZE - 14, 0), #'Curium' : (MAX_SIZE - 13, 0), #'Berkelium' : (MAX_SIZE - 12, 0), #'Californium' : (MAX_SIZE - 11, 0), #'Einsteinium' : (MAX_SIZE - 10, 0), #'Fermium' : (MAX_SIZE - 9, 0), #'Mendelevium' : (MAX_SIZE - 8, 0), #'Nobelium' : (MAX_SIZE - 7, 0), #'Lawrencium' : (MAX_SIZE - 6, 0), #'Rutherfordium': (MAX_SIZE - 5, 0), #'Dubnium' : (MAX_SIZE - 4, 0), #'Seaborgium' : (MAX_SIZE - 3, 0), #'Bohrium' : (MAX_SIZE - 2, 0), #'Hassium' : (MAX_SIZE - 1, 0), #'Meitnerium' : (MAX_SIZE - 0, 0), # <---- Please refrain from fixing PEP-8 E203 and E265 ------ # pylint: enable=E8203,E8265 } LNAMES = dict((k.lower(), v) for (k, v) in iter(NAMES.items())) VNAMES = dict((v, k) for (k, v) in iter(NAMES.items())) RMATCH = dict((v[:2], k) for (k, v) in iter(NAMES.items())) def __init__(self, # pylint: disable=C0103 major, minor, bugfix=0, mbugfix=0, pre_type=None, pre_num=None, noc=0, sha=None): if isinstance(major, string_types): major = int(major) if isinstance(minor, string_types): minor = int(minor) if bugfix is None: bugfix = 0 elif isinstance(bugfix, string_types): bugfix = int(bugfix) if mbugfix is None: mbugfix = 0 elif isinstance(mbugfix, string_types): mbugfix = int(mbugfix) if pre_type is None: pre_type = '' if pre_num is None: pre_num = 0 elif isinstance(pre_num, string_types): pre_num = int(pre_num) if noc is None: noc = 0 elif isinstance(noc, string_types) and noc == 'n/a': noc = -1 elif isinstance(noc, string_types): noc = int(noc) self.major = major self.minor = minor self.bugfix = bugfix self.mbugfix = mbugfix self.pre_type = pre_type self.pre_num = pre_num self.name = self.VNAMES.get((major, minor), None) self.noc = noc self.sha = sha @classmethod def parse(cls, version_string): if version_string.lower() in cls.LNAMES: return cls.from_name(version_string) vstr = version_string.decode() if isinstance(version_string, bytes) else version_string match = cls.git_describe_regex.match(vstr) if not match: raise ValueError( 'Unable to parse version string: \'{0}\''.format(version_string) ) return cls(*match.groups()) @classmethod def from_name(cls, name): if name.lower() not in cls.LNAMES: raise ValueError( 'Named version \'{0}\' is not known'.format(name) ) return cls(*cls.LNAMES[name.lower()]) @classmethod def from_last_named_version(cls): return cls.from_name( cls.VNAMES[ max([version_info for version_info in cls.VNAMES if version_info[0] < (MAX_SIZE - 200)]) ] ) @classmethod def next_release(cls): return cls.from_name( cls.VNAMES[ min([version_info for version_info in cls.VNAMES if version_info > cls.from_last_named_version().info]) ] ) @property def sse(self): # Higher than 0.17, lower than first date based return 0 < self.major < 2014 @property def info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix ) @property def pre_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num ) @property def noc_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc ) @property def full_info(self): return ( self.major, self.minor, self.bugfix, self.mbugfix, self.pre_type, self.pre_num, self.noc, self.sha ) @property def string(self): version_string = '{0}.{1}.{2}'.format( self.major, self.minor, self.bugfix ) if self.mbugfix: version_string += '.{0}'.format(self.mbugfix) if self.pre_type: version_string += '{0}{1}'.format(self.pre_type, self.pre_num) if self.noc and self.sha: noc = self.noc if noc < 0: noc = 'n/a' version_string += '-{0}-{1}'.format(noc, self.sha) return version_string @property def formatted_version(self): if self.name and self.major > 10000: version_string = self.name if self.sse: version_string += ' Enterprise' version_string += ' (Unreleased)' return version_string version_string = self.string if self.sse: version_string += ' Enterprise' if (self.major, self.minor) in self.RMATCH: version_string += ' ({0})'.format(self.RMATCH[(self.major, self.minor)]) return version_string def __str__(self): return self.string def __compare__(self, other, method): if not isinstance(other, SaltStackVersion): if isinstance(other, string_types): other = SaltStackVersion.parse(other) elif isinstance(other, (list, tuple)): other = SaltStackVersion(*other) else: raise ValueError( 'Cannot instantiate Version from type \'{0}\''.format( type(other) ) ) if (self.pre_type and other.pre_type) or (not self.pre_type and not other.pre_type): # Both either have or don't have pre-release information, regular compare is ok return method(self.noc_info, other.noc_info) if self.pre_type and not other.pre_type: # We have pre-release information, the other side doesn't other_noc_info = list(other.noc_info) other_noc_info[4] = 'zzzzz' return method(self.noc_info, tuple(other_noc_info)) if not self.pre_type and other.pre_type: # The other side has pre-release informatio, we don't noc_info = list(self.noc_info) noc_info[4] = 'zzzzz' return method(tuple(noc_info), other.noc_info) def __lt__(self, other): return self.__compare__(other, lambda _self, _other: _self < _other) def __le__(self, other): return self.__compare__(other, lambda _self, _other: _self <= _other) def __eq__(self, other): return self.__compare__(other, lambda _self, _other: _self == _other) def __ne__(self, other): return self.__compare__(other, lambda _self, _other: _self != _other) def __ge__(self, other): return self.__compare__(other, lambda _self, _other: _self >= _other) def __gt__(self, other): return self.__compare__(other, lambda _self, _other: _self > _other) def __repr__(self): parts = [] if self.name: parts.append('name=\'{0}\''.format(self.name)) parts.extend([ 'major={0}'.format(self.major), 'minor={0}'.format(self.minor), 'bugfix={0}'.format(self.bugfix) ]) if self.mbugfix: parts.append('minor-bugfix={0}'.format(self.mbugfix)) if self.pre_type: parts.append('{0}={1}'.format(self.pre_type, self.pre_num)) noc = self.noc if noc == -1: noc = 'n/a' if noc and self.sha: parts.extend([ 'noc={0}'.format(noc), 'sha={0}'.format(self.sha) ]) return '<{0} {1}>'.format(self.__class__.__name__, ' '.join(parts)) # ----- Hardcoded Salt Codename Version Information -----------------------------------------------------------------> # # There's no need to do anything here. The last released codename will be picked up # -------------------------------------------------------------------------------------------------------------------- __saltstack_version__ = SaltStackVersion.from_last_named_version() # <---- Hardcoded Salt Version Information --------------------------------------------------------------------------- # ----- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------> def __discover_version(saltstack_version): # This might be a 'python setup.py develop' installation type. Let's # discover the version information at runtime. import os import subprocess if 'SETUP_DIRNAME' in globals(): # This is from the exec() call in Salt's setup.py cwd = SETUP_DIRNAME # pylint: disable=E0602 if not os.path.exists(os.path.join(cwd, '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version else: cwd = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(os.path.join(os.path.dirname(cwd), '.git')): # This is not a Salt git checkout!!! Don't even try to parse... return saltstack_version try: kwargs = dict( stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) if not sys.platform.startswith('win'): # Let's not import `salt.utils` for the above check kwargs['close_fds'] = True process = subprocess.Popen( ['git', 'describe', '--tags', '--first-parent', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if process.returncode != 0: # The git version running this might not support --first-parent # Revert to old command process = subprocess.Popen( ['git', 'describe', '--tags', '--match', 'v[0-9]*', '--always'], **kwargs) out, err = process.communicate() if six.PY3: out = out.decode() err = err.decode() out = out.strip() err = err.strip() if not out or err: return saltstack_version try: return SaltStackVersion.parse(out) except ValueError: if not SaltStackVersion.git_sha_regex.match(out): raise # We only define the parsed SHA and set NOC as ??? (unknown) saltstack_version.sha = out.strip() saltstack_version.noc = -1 except OSError as os_err: if os_err.errno != 2: # If the errno is not 2(The system cannot find the file # specified), raise the exception so it can be catch by the # developers raise return saltstack_version def __get_version(saltstack_version): ''' If we can get a version provided at installation time or from Git, use that instead, otherwise we carry on. ''' try: # Try to import the version information provided at install time from salt._version import __saltstack_version__ # pylint: disable=E0611,F0401 return __saltstack_version__ except ImportError: return __discover_version(saltstack_version) # Get additional version information if available __saltstack_version__ = __get_version(__saltstack_version__) # This function has executed once, we're done with it. Delete it! del __get_version # <---- Dynamic/Runtime Salt Version Information --------------------------------------------------------------------- # ----- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------> __version_info__ = __saltstack_version__.info __version__ = __saltstack_version__.string # <---- Common version related attributes - NO NEED TO CHANGE -------------------------------------------------------- def salt_information(): ''' Report version of salt. ''' yield 'Salt', __version__ def dependency_information(include_salt_cloud=False): ''' Report versions of library dependencies. ''' libs = [ ('Python', None, sys.version.rsplit('\n')[0].strip()), ('Jinja2', 'jinja2', '__version__'), ('M2Crypto', 'M2Crypto', 'version'), ('msgpack-python', 'msgpack', 'version'), ('msgpack-pure', 'msgpack_pure', 'version'), ('pycrypto', 'Crypto', '__version__'), ('pycryptodome', 'Cryptodome', 'version_info'), ('PyYAML', 'yaml', '__version__'), ('PyZMQ', 'zmq', '__version__'), ('ZMQ', 'zmq', 'zmq_version'), ('Mako', 'mako', '__version__'), ('Tornado', 'tornado', 'version'), ('timelib', 'timelib', 'version'), ('dateutil', 'dateutil', '__version__'), ('pygit2', 'pygit2', '__version__'), ('libgit2', 'pygit2', 'LIBGIT2_VERSION'), ('smmap', 'smmap', '__version__'), ('cffi', 'cffi', '__version__'), ('pycparser', 'pycparser', '__version__'), ('gitdb', 'gitdb', '__version__'), ('gitpython', 'git', '__version__'), ('python-gnupg', 'gnupg', '__version__'), ('mysql-python', 'MySQLdb', '__version__'), ('cherrypy', 'cherrypy', '__version__'), ('docker-py', 'docker', '__version__'), ] if include_salt_cloud: libs.append( ('Apache Libcloud', 'libcloud', '__version__'), ) for name, imp, attr in libs: if imp is None: yield name, attr continue try: imp = __import__(imp) version = getattr(imp, attr) if callable(version): version = version() if isinstance(version, (tuple, list)): version = '.'.join(map(str, version)) yield name, version except Exception: yield name, None def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return ' '.join(lin_ver) elif mac_ver[0]: if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]): return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]]) else: return ' '.join([mac_ver[0], mac_ver[2]]) elif win_ver[0]: return ' '.join(win_ver) else: return '' if platform.win32_ver()[0]: # Get the version and release info based on the Windows Operating # System Product Name. As long as Microsoft maintains a similar format # this should be future proof import win32api # pylint: disable=3rd-party-module-not-gated import win32con # pylint: disable=3rd-party-module-not-gated # Get the product name from the registry hkey = win32con.HKEY_LOCAL_MACHINE key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' value_name = 'ProductName' reg_handle = win32api.RegOpenKey(hkey, key) # Returns a tuple of (product_name, value_type) product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name) version = 'Unknown' release = '' if 'Server' in product_name: for item in product_name.split(' '): # If it's all digits, then it's version if re.match(r'\d+', item): version = item # If it starts with R and then numbers, it's the release # ie: R2 if re.match(r'^R\d+$', item): release = item release = '{0}Server{1}'.format(version, release) else: for item in product_name.split(' '): # If it's a number, decimal number, Thin or Vista, then it's the # version if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item): version = item release = version _, ver, sp, extra = platform.win32_ver() version = ' '.join([release, ver, sp, extra]) else: version = system_version() release = platform.release() system = [ ('system', platform.system()), ('dist', ' '.join(linux_distribution(full_distribution_name=False))), ('release', release), ('machine', platform.machine()), ('version', version), ('locale', __salt_system_encoding__), ] for name, attr in system: yield name, attr continue def versions_information(include_salt_cloud=False): ''' Report the versions of dependent software. ''' salt_info = list(salt_information()) lib_info = list(dependency_information(include_salt_cloud)) sys_info = list(system_information()) return {'Salt Version': dict(salt_info), 'Dependency Versions': dict(lib_info), 'System Versions': dict(sys_info)} def versions_report(include_salt_cloud=False): ''' Yield each version properly formatted for console output. ''' ver_info = versions_information(include_salt_cloud) lib_pad = max(len(name) for name in ver_info['Dependency Versions']) sys_pad = max(len(name) for name in ver_info['System Versions']) padding = max(lib_pad, sys_pad) + 1 fmt = '{0:>{pad}}: {1}' info = [] for ver_type in ('Salt Version', 'Dependency Versions', 'System Versions'): info.append('{0}:'.format(ver_type)) # List dependencies in alphabetical, case insensitive order for name in sorted(ver_info[ver_type], key=lambda x: x.lower()): ver = fmt.format(name, ver_info[ver_type][name] or 'Not Installed', pad=padding) info.append(ver) info.append(' ') for line in info: yield line if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'msi': # Building the msi requires an msi-conformant version print(msi_conformant_version()) else: print(__version__)
saltstack/salt
salt/states/winrepo.py
genrepo
python
def genrepo(name, force=False, allow_empty=False): ''' Refresh the winrepo.p file of the repository (salt-run winrepo.genrepo) If ``force`` is ``True`` no checks will be made and the repository will be generated if ``allow_empty`` is ``True`` then the state will not return an error if there are 0 packages, .. note:: This state only loads on minions that have the ``roles: salt-master`` grain set. Example: .. code-block:: yaml winrepo: winrepo.genrepo ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} master_config = salt.config.master_config( os.path.join(salt.syspaths.CONFIG_DIR, 'master') ) winrepo_dir = master_config['winrepo_dir'] winrepo_cachefile = master_config['winrepo_cachefile'] # We're actually looking for the full path to the cachefile here, so # prepend the winrepo_dir winrepo_cachefile = os.path.join(winrepo_dir, winrepo_cachefile) # Check if the winrepo directory exists # if not search for a file with a newer mtime than the winrepo_cachefile file execute = False if not force: if not os.path.exists(winrepo_dir): ret['result'] = False ret['comment'] = '{0} is missing'.format(winrepo_dir) return ret elif not os.path.exists(winrepo_cachefile): execute = True ret['comment'] = '{0} is missing'.format(winrepo_cachefile) else: winrepo_cachefile_mtime = os.stat(winrepo_cachefile)[stat.ST_MTIME] for root, dirs, files in salt.utils.path.os_walk(winrepo_dir): for name in itertools.chain(files, dirs): full_path = os.path.join(root, name) if os.stat(full_path)[stat.ST_MTIME] > winrepo_cachefile_mtime: ret['comment'] = 'mtime({0}) < mtime({1})'.format(winrepo_cachefile, full_path) execute = True break if __opts__['test']: ret['result'] = None return ret if not execute and not force: return ret runner = salt.runner.RunnerClient(master_config) runner_ret = runner.cmd('winrepo.genrepo', []) ret['changes'] = {'winrepo': runner_ret} if isinstance(runner_ret, dict) and runner_ret == {} and not allow_empty: os.remove(winrepo_cachefile) ret['result'] = False ret['comment'] = 'winrepo.genrepo returned empty' return ret
Refresh the winrepo.p file of the repository (salt-run winrepo.genrepo) If ``force`` is ``True`` no checks will be made and the repository will be generated if ``allow_empty`` is ``True`` then the state will not return an error if there are 0 packages, .. note:: This state only loads on minions that have the ``roles: salt-master`` grain set. Example: .. code-block:: yaml winrepo: winrepo.genrepo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/winrepo.py#L23-L95
[ "def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):\n '''\n Reads in the master configuration file and sets up default options\n\n This is useful for running the actual master daemon. For running\n Master-side client interfaces that need the master opts see\n :py:func:`salt.client.client_config`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n if not os.environ.get(env_var, None):\n # No valid setting was given using the configuration variable.\n # Lets see is SALT_CONFIG_DIR is of any use\n salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)\n if salt_config_dir:\n env_config_file_path = os.path.join(salt_config_dir, 'master')\n if salt_config_dir and os.path.isfile(env_config_file_path):\n # We can get a configuration file using SALT_CONFIG_DIR, let's\n # update the environment with this information\n os.environ[env_var] = env_config_file_path\n\n overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])\n default_include = overrides.get('default_include',\n defaults['default_include'])\n include = overrides.get('include', [])\n\n overrides.update(include_config(default_include, path, verbose=False,\n exit_on_config_errors=exit_on_config_errors))\n overrides.update(include_config(include, path, verbose=True,\n exit_on_config_errors=exit_on_config_errors))\n opts = apply_master_config(overrides, defaults)\n _validate_ssh_minion_opts(opts)\n _validate_opts(opts)\n # If 'nodegroups:' is uncommented in the master config file, and there are\n # no nodegroups defined, opts['nodegroups'] will be None. Fix this by\n # reverting this value to the default, as if 'nodegroups:' was commented\n # out or not present.\n if opts.get('nodegroups') is None:\n opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})\n if salt.utils.data.is_dictlist(opts['nodegroups']):\n opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])\n apply_sdb(opts)\n return opts\n", "def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):\n '''\n Execute a function\n '''\n return super(RunnerClient, self).cmd(fun,\n arg,\n pub_data,\n kwarg,\n print_event,\n full_return)\n" ]
# -*- coding: utf-8 -*- ''' Manage Windows Package Repository ''' from __future__ import absolute_import, unicode_literals, print_function # Python Libs import os import stat import itertools # Salt Modules import salt.runner import salt.config import salt.syspaths import salt.utils.path def __virtual__(): return 'winrepo'
saltstack/salt
salt/beacons/__init__.py
Beacon.process
python
def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret
Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L31-L131
[ "def running(opts):\n '''\n Return the running jobs on this minion\n '''\n\n ret = []\n proc_dir = os.path.join(opts['cachedir'], 'proc')\n if not os.path.isdir(proc_dir):\n return ret\n for fn_ in os.listdir(proc_dir):\n path = os.path.join(proc_dir, fn_)\n try:\n data = _read_proc_file(path, opts)\n if data is not None:\n ret.append(data)\n except (IOError, OSError):\n # proc files may be removed at any time during this process by\n # the minion process that is executing the JID in question, so\n # we must ignore ENOENT during this process\n pass\n return ret\n", "def _trim_config(self, b_config, mod, key):\n '''\n Take a beacon configuration and strip out the interval bits\n '''\n if isinstance(b_config[mod], list):\n self._remove_list_item(b_config[mod], key)\n elif isinstance(b_config[mod], dict):\n b_config[mod].pop(key)\n return b_config\n", "def _determine_beacon_config(self, current_beacon_config, key):\n '''\n Process a beacon configuration to determine its interval\n '''\n\n interval = False\n if isinstance(current_beacon_config, dict):\n interval = current_beacon_config.get(key, False)\n\n return interval\n", "def _process_interval(self, mod, interval):\n '''\n Process beacons with intervals\n Return True if a beacon should be run on this loop\n '''\n log.trace('Processing interval %s for beacon mod %s', interval, mod)\n loop_interval = self.opts['loop_interval']\n if mod in self.interval_map:\n log.trace('Processing interval in map')\n counter = self.interval_map[mod]\n log.trace('Interval counter: %s', counter)\n if counter * loop_interval >= interval:\n self.interval_map[mod] = 1\n return True\n else:\n self.interval_map[mod] += 1\n else:\n log.trace('Interval process inserting mod: %s', mod)\n self.interval_map[mod] = 1\n return False\n", "def _remove_list_item(self, beacon_config, label):\n '''\n Remove an item from a beacon config list\n '''\n\n index = self._get_index(beacon_config, label)\n del beacon_config[index]\n" ]
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon._trim_config
python
def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config
Take a beacon configuration and strip out the interval bits
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L133-L141
null
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon._determine_beacon_config
python
def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval
Process a beacon configuration to determine its interval
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L143-L152
null
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon._process_interval
python
def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False
Process beacons with intervals Return True if a beacon should be run on this loop
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L154-L173
null
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon._get_index
python
def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0]
Return the index of a labeled config item in the beacon config, -1 if the index is not found
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L175-L184
null
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon._remove_list_item
python
def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index]
Remove an item from a beacon config list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L186-L192
null
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon._update_enabled
python
def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value})
Update whether an individual beacon is enabled
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L194-L207
null
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon._get_beacons
python
def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons
Return the beacons data structure
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L209-L226
null
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon.list_beacons
python
def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True
List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L228-L247
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def _get_beacons(self,\n include_opts=True,\n include_pillar=True):\n '''\n Return the beacons data structure\n '''\n beacons = {}\n if include_pillar:\n pillar_beacons = self.opts.get('pillar', {}).get('beacons', {})\n if not isinstance(pillar_beacons, dict):\n raise ValueError('Beacons must be of type dict.')\n beacons.update(pillar_beacons)\n if include_opts:\n opts_beacons = self.opts.get('beacons', {})\n if not isinstance(opts_beacons, dict):\n raise ValueError('Beacons must be of type dict.')\n beacons.update(opts_beacons)\n return beacons\n", "def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n" ]
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon.list_available_beacons
python
def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True
List the available beacons
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L249-L261
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n" ]
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon.validate_beacon
python
def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True
Return available beacon functions
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L263-L286
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n" ]
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon.add_beacon
python
def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True
Add a beacon item
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L288-L315
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def _get_beacons(self,\n include_opts=True,\n include_pillar=True):\n '''\n Return the beacons data structure\n '''\n beacons = {}\n if include_pillar:\n pillar_beacons = self.opts.get('pillar', {}).get('beacons', {})\n if not isinstance(pillar_beacons, dict):\n raise ValueError('Beacons must be of type dict.')\n beacons.update(pillar_beacons)\n if include_opts:\n opts_beacons = self.opts.get('beacons', {})\n if not isinstance(opts_beacons, dict):\n raise ValueError('Beacons must be of type dict.')\n beacons.update(opts_beacons)\n return beacons\n", "def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n" ]
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon.delete_beacon
python
def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True
Delete a beacon item
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L342-L365
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def _get_beacons(self,\n include_opts=True,\n include_pillar=True):\n '''\n Return the beacons data structure\n '''\n beacons = {}\n if include_pillar:\n pillar_beacons = self.opts.get('pillar', {}).get('beacons', {})\n if not isinstance(pillar_beacons, dict):\n raise ValueError('Beacons must be of type dict.')\n beacons.update(pillar_beacons)\n if include_opts:\n opts_beacons = self.opts.get('beacons', {})\n if not isinstance(opts_beacons, dict):\n raise ValueError('Beacons must be of type dict.')\n beacons.update(opts_beacons)\n return beacons\n", "def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n" ]
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon.enable_beacons
python
def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True
Enable beacons
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L367-L379
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n" ]
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/beacons/__init__.py
Beacon.disable_beacons
python
def disable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = False # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True
Enable beacons
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L381-L393
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n" ]
class Beacon(object): ''' This class is used to evaluate and execute on the beacon system ''' def __init__(self, opts, functions): self.opts = opts self.functions = functions self.beacons = salt.loader.beacons(opts, functions) self.interval_map = dict() def process(self, config, grains): ''' Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - files: - /etc/fstab: {} - /var/cache/foo: {} ''' ret = [] b_config = copy.deepcopy(config) if 'enabled' in b_config and not b_config['enabled']: return for mod in config: if mod == 'enabled': continue # Convert beacons that are lists to a dict to make processing easier current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {} list(map(current_beacon_config.update, config[mod])) elif isinstance(config[mod], dict): current_beacon_config = config[mod] if 'enabled' in current_beacon_config: if not current_beacon_config['enabled']: log.trace('Beacon %s disabled', mod) continue else: # remove 'enabled' item before processing the beacon if isinstance(config[mod], dict): del config[mod]['enabled'] else: self._remove_list_item(config[mod], 'enabled') log.trace('Beacon processing: %s', mod) beacon_name = None if self._determine_beacon_config(current_beacon_config, 'beacon_module'): beacon_name = current_beacon_config['beacon_module'] else: beacon_name = mod fun_str = '{0}.beacon'.format(beacon_name) validate_str = '{0}.validate'.format(beacon_name) if fun_str in self.beacons: runonce = self._determine_beacon_config(current_beacon_config, 'run_once') interval = self._determine_beacon_config(current_beacon_config, 'interval') if interval: b_config = self._trim_config(b_config, mod, 'interval') if not self._process_interval(mod, interval): log.trace('Skipping beacon %s. Interval not reached.', mod) continue if self._determine_beacon_config(current_beacon_config, 'disable_during_state_run'): log.trace('Evaluting if beacon %s should be skipped due to a state run.', mod) b_config = self._trim_config(b_config, mod, 'disable_during_state_run') is_running = False running_jobs = salt.utils.minion.running(self.opts) for job in running_jobs: if re.match('state.*', job['fun']): is_running = True if is_running: close_str = '{0}.close'.format(beacon_name) if close_str in self.beacons: log.info('Closing beacon %s. State run in progress.', mod) self.beacons[close_str](b_config[mod]) else: log.info('Skipping beacon %s. State run in progress.', mod) continue # Update __grains__ on the beacon self.beacons[fun_str].__globals__['__grains__'] = grains # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: valid, vcomment = self.beacons[validate_str](b_config[mod]) if not valid: log.info('Beacon %s configuration invalid, ' 'not running.\n%s', mod, vcomment) continue # Fire the beacon! raw = self.beacons[fun_str](b_config[mod]) for data in raw: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) if 'tag' in data: tag += data.pop('tag') if 'id' not in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data, 'beacon_name': beacon_name}) if runonce: self.disable_beacon(mod) else: log.warning('Unable to process beacon %s', mod) return ret def _trim_config(self, b_config, mod, key): ''' Take a beacon configuration and strip out the interval bits ''' if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.interval_map: log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: %s', counter) if counter * loop_interval >= interval: self.interval_map[mod] = 1 return True else: self.interval_map[mod] += 1 else: log.trace('Interval process inserting mod: %s', mod) self.interval_map[mod] = 1 return False def _get_index(self, beacon_config, label): ''' Return the index of a labeled config item in the beacon config, -1 if the index is not found ''' indexes = [index for index, item in enumerate(beacon_config) if label in item] if not indexes: return -1 else: return indexes[0] def _remove_list_item(self, beacon_config, label): ''' Remove an item from a beacon config list ''' index = self._get_index(beacon_config, label) del beacon_config[index] def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if enabled_index >= 0: self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value else: self.opts['beacons'][name].append({'enabled': enabled_value}) def _get_beacons(self, include_opts=True, include_pillar=True): ''' Return the beacons data structure ''' beacons = {} if include_pillar: pillar_beacons = self.opts.get('pillar', {}).get('beacons', {}) if not isinstance(pillar_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(pillar_beacons) if include_opts: opts_beacons = self.opts.get('beacons', {}) if not isinstance(opts_beacons, dict): raise ValueError('Beacons must be of type dict.') beacons.update(opts_beacons) return beacons def list_beacons(self, include_pillar=True, include_opts=True): ''' List the beacon items include_pillar: Whether to include beacons that are configured in pillar, default is True. include_opts: Whether to include beacons that are configured in opts, default is True. ''' beacons = self._get_beacons(include_pillar, include_opts) # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': beacons}, tag='/salt/minion/minion_beacons_list_complete') return True def list_available_beacons(self): ''' List the available beacons ''' _beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon] # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': _beacons}, tag='/salt/minion/minion_beacons_list_available_complete') return True def validate_beacon(self, name, beacon_data): ''' Return available beacon functions ''' validate_str = '{}.validate'.format(name) # Run the validate function if it's available, # otherwise there is a warning about it being missing if validate_str in self.beacons: if 'enabled' in beacon_data: del beacon_data['enabled'] valid, vcomment = self.beacons[validate_str](beacon_data) else: vcomment = 'Beacon {0} does not have a validate' \ ' function, skipping validation.'.format(name) valid = True # Fire the complete event back along with the list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'vcomment': vcomment, 'valid': valid}, tag='/salt/minion/minion_beacon_validation_complete') return True def add_beacon(self, name, beacon_data): ''' Add a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot update beacon item {0}, ' \ 'because it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) else: comment = 'Added new beacon item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_add_complete') return True def modify_beacon(self, name, beacon_data): ''' Modify a beacon item ''' data = {} data[name] = beacon_data if name in self._get_beacons(include_opts=False): comment = 'Cannot modify beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: comment = 'Updating settings for beacon ' \ 'item: {0}'.format(name) complete = True self.opts['beacons'].update(data) # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_modify_complete') return True def delete_beacon(self, name): ''' Delete a beacon item ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot delete beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: if name in self.opts['beacons']: del self.opts['beacons'][name] comment = 'Deleting beacon item: {0}'.format(name) else: comment = 'Beacon item {0} not found.'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_complete') return True def enable_beacons(self): ''' Enable beacons ''' self.opts['beacons']['enabled'] = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True def enable_beacon(self, name): ''' Enable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot enable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, True) comment = 'Enabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True def disable_beacon(self, name): ''' Disable a beacon ''' if name in self._get_beacons(include_opts=False): comment = 'Cannot disable beacon item {0}, ' \ 'it is configured in pillar.'.format(name) complete = False else: self._update_enabled(name, False) comment = 'Disabling beacon item {0}'.format(name) complete = True # Fire the complete event back along with updated list of beacons evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': complete, 'comment': comment, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True def reset(self): ''' Reset the beacons to defaults ''' self.opts['beacons'] = {}
saltstack/salt
salt/modules/macpackage.py
install
python
def install(pkg, target='LocalSystem', store=False, allow_untrusted=False): ''' Install a pkg file Args: pkg (str): The package to install target (str): The target in which to install the package to store (bool): Should the package be installed as if it was from the store? allow_untrusted (bool): Allow the installation of untrusted packages? Returns: dict: A dictionary containing the results of the installation CLI Example: .. code-block:: bash salt '*' macpackage.install test.pkg ''' if '*.' not in pkg: # If we use wildcards, we cannot use quotes pkg = _quote(pkg) target = _quote(target) cmd = 'installer -pkg {0} -target {1}'.format(pkg, target) if store: cmd += ' -store' if allow_untrusted: cmd += ' -allowUntrusted' # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True return __salt__['cmd.run_all'](cmd, python_shell=python_shell)
Install a pkg file Args: pkg (str): The package to install target (str): The target in which to install the package to store (bool): Should the package be installed as if it was from the store? allow_untrusted (bool): Allow the installation of untrusted packages? Returns: dict: A dictionary containing the results of the installation CLI Example: .. code-block:: bash salt '*' macpackage.install test.pkg
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macpackage.py#L43-L81
null
# -*- coding: utf-8 -*- ''' Install pkg, dmg and .app applications on macOS minions. ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import os import logging import shlex try: import pipes HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'macpackage' if hasattr(shlex, 'quote'): _quote = shlex.quote elif HAS_DEPS and hasattr(pipes, 'quote'): _quote = pipes.quote else: _quote = None def __virtual__(): ''' Only work on Mac OS ''' if salt.utils.platform.is_darwin() and _quote is not None: return __virtualname__ return False def install_app(app, target='/Applications/'): ''' Install an app file by moving it into the specified Applications directory Args: app (str): The location of the .app file target (str): The target in which to install the package to Default is ''/Applications/'' Returns: str: The results of the rsync command CLI Example: .. code-block:: bash salt '*' macpackage.install_app /tmp/tmp.app /Applications/ ''' if target[-4:] != '.app': if app[-1:] == '/': base_app = os.path.basename(app[:-1]) else: base_app = os.path.basename(app) target = os.path.join(target, base_app) if not app[-1] == '/': app += '/' cmd = 'rsync -a --delete "{0}" "{1}"'.format(app, target) return __salt__['cmd.run'](cmd) def uninstall_app(app): ''' Uninstall an app file by removing it from the Applications directory Args: app (str): The location of the .app file Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' macpackage.uninstall_app /Applications/app.app ''' return __salt__['file.remove'](app) def mount(dmg): ''' Attempt to mount a dmg file to a temporary location and return the location of the pkg file inside Args: dmg (str): The location of the dmg file to mount Returns: tuple: Tuple containing the results of the command along with the mount point CLI Example: .. code-block:: bash salt '*' macpackage.mount /tmp/software.dmg ''' temp_dir = __salt__['temp.dir'](prefix='dmg-') cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {0} "{1}"'.format(temp_dir, dmg) return __salt__['cmd.run'](cmd), temp_dir def unmount(mountpoint): ''' Attempt to unmount a dmg file from a temporary location Args: mountpoint (str): The location of the mount point Returns: str: The results of the hdutil detach command CLI Example: .. code-block:: bash salt '*' macpackage.unmount /dev/disk2 ''' cmd = 'hdiutil detach "{0}"'.format(mountpoint) return __salt__['cmd.run'](cmd) def installed_pkgs(): ''' Return the list of installed packages on the machine Returns: list: List of installed packages CLI Example: .. code-block:: bash salt '*' macpackage.installed_pkgs ''' cmd = 'pkgutil --pkgs' return __salt__['cmd.run'](cmd).split('\n') def get_pkg_id(pkg): ''' Attempt to get the package ID from a .pkg file Args: pkg (str): The location of the pkg file Returns: list: List of all of the package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_pkg_id /tmp/test.pkg ''' pkg = _quote(pkg) package_ids = [] # Create temp directory temp_dir = __salt__['temp.dir'](prefix='pkg-') try: # List all of the PackageInfo files cmd = 'xar -t -f {0} | grep PackageInfo'.format(pkg) out = __salt__['cmd.run'](cmd, python_shell=True, output_loglevel='quiet') files = out.split('\n') if 'Error opening' not in out: # Extract the PackageInfo files cmd = 'xar -x -f {0} {1}'.format(pkg, ' '.join(files)) __salt__['cmd.run'](cmd, cwd=temp_dir, output_loglevel='quiet') # Find our identifiers for f in files: i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f)) if i: package_ids.extend(i) else: package_ids = _get_pkg_id_dir(pkg) finally: # Clean up __salt__['file.remove'](temp_dir) return package_ids def get_mpkg_ids(mpkg): ''' Attempt to get the package IDs from a mounted .mpkg file Args: mpkg (str): The location of the mounted mpkg file Returns: list: List of package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_mpkg_ids /dev/disk2 ''' mpkg = _quote(mpkg) package_infos = [] base_path = os.path.dirname(mpkg) # List all of the .pkg files cmd = 'find {0} -name *.pkg'.format(base_path) out = __salt__['cmd.run'](cmd, python_shell=True) pkg_files = out.split('\n') for p in pkg_files: package_infos.extend(get_pkg_id(p)) return package_infos def _get_pkg_id_from_pkginfo(pkginfo): # Find our identifiers pkginfo = _quote(pkginfo) cmd = 'cat {0} | grep -Eo \'identifier="[a-zA-Z.0-9\\-]*"\' | cut -c 13- | tr -d \'"\''.format(pkginfo) out = __salt__['cmd.run'](cmd, python_shell=True) if 'No such file' not in out: return out.split('\n') return [] def _get_pkg_id_dir(path): path = _quote(os.path.join(path, 'Contents/Info.plist')) cmd = '/usr/libexec/PlistBuddy -c "print :CFBundleIdentifier" {0}'.format(path) # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True out = __salt__['cmd.run'](cmd, python_shell=python_shell) if 'Does Not Exist' not in out: return [out] return []
saltstack/salt
salt/modules/macpackage.py
install_app
python
def install_app(app, target='/Applications/'): ''' Install an app file by moving it into the specified Applications directory Args: app (str): The location of the .app file target (str): The target in which to install the package to Default is ''/Applications/'' Returns: str: The results of the rsync command CLI Example: .. code-block:: bash salt '*' macpackage.install_app /tmp/tmp.app /Applications/ ''' if target[-4:] != '.app': if app[-1:] == '/': base_app = os.path.basename(app[:-1]) else: base_app = os.path.basename(app) target = os.path.join(target, base_app) if not app[-1] == '/': app += '/' cmd = 'rsync -a --delete "{0}" "{1}"'.format(app, target) return __salt__['cmd.run'](cmd)
Install an app file by moving it into the specified Applications directory Args: app (str): The location of the .app file target (str): The target in which to install the package to Default is ''/Applications/'' Returns: str: The results of the rsync command CLI Example: .. code-block:: bash salt '*' macpackage.install_app /tmp/tmp.app /Applications/
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macpackage.py#L84-L115
null
# -*- coding: utf-8 -*- ''' Install pkg, dmg and .app applications on macOS minions. ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import os import logging import shlex try: import pipes HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'macpackage' if hasattr(shlex, 'quote'): _quote = shlex.quote elif HAS_DEPS and hasattr(pipes, 'quote'): _quote = pipes.quote else: _quote = None def __virtual__(): ''' Only work on Mac OS ''' if salt.utils.platform.is_darwin() and _quote is not None: return __virtualname__ return False def install(pkg, target='LocalSystem', store=False, allow_untrusted=False): ''' Install a pkg file Args: pkg (str): The package to install target (str): The target in which to install the package to store (bool): Should the package be installed as if it was from the store? allow_untrusted (bool): Allow the installation of untrusted packages? Returns: dict: A dictionary containing the results of the installation CLI Example: .. code-block:: bash salt '*' macpackage.install test.pkg ''' if '*.' not in pkg: # If we use wildcards, we cannot use quotes pkg = _quote(pkg) target = _quote(target) cmd = 'installer -pkg {0} -target {1}'.format(pkg, target) if store: cmd += ' -store' if allow_untrusted: cmd += ' -allowUntrusted' # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True return __salt__['cmd.run_all'](cmd, python_shell=python_shell) def uninstall_app(app): ''' Uninstall an app file by removing it from the Applications directory Args: app (str): The location of the .app file Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' macpackage.uninstall_app /Applications/app.app ''' return __salt__['file.remove'](app) def mount(dmg): ''' Attempt to mount a dmg file to a temporary location and return the location of the pkg file inside Args: dmg (str): The location of the dmg file to mount Returns: tuple: Tuple containing the results of the command along with the mount point CLI Example: .. code-block:: bash salt '*' macpackage.mount /tmp/software.dmg ''' temp_dir = __salt__['temp.dir'](prefix='dmg-') cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {0} "{1}"'.format(temp_dir, dmg) return __salt__['cmd.run'](cmd), temp_dir def unmount(mountpoint): ''' Attempt to unmount a dmg file from a temporary location Args: mountpoint (str): The location of the mount point Returns: str: The results of the hdutil detach command CLI Example: .. code-block:: bash salt '*' macpackage.unmount /dev/disk2 ''' cmd = 'hdiutil detach "{0}"'.format(mountpoint) return __salt__['cmd.run'](cmd) def installed_pkgs(): ''' Return the list of installed packages on the machine Returns: list: List of installed packages CLI Example: .. code-block:: bash salt '*' macpackage.installed_pkgs ''' cmd = 'pkgutil --pkgs' return __salt__['cmd.run'](cmd).split('\n') def get_pkg_id(pkg): ''' Attempt to get the package ID from a .pkg file Args: pkg (str): The location of the pkg file Returns: list: List of all of the package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_pkg_id /tmp/test.pkg ''' pkg = _quote(pkg) package_ids = [] # Create temp directory temp_dir = __salt__['temp.dir'](prefix='pkg-') try: # List all of the PackageInfo files cmd = 'xar -t -f {0} | grep PackageInfo'.format(pkg) out = __salt__['cmd.run'](cmd, python_shell=True, output_loglevel='quiet') files = out.split('\n') if 'Error opening' not in out: # Extract the PackageInfo files cmd = 'xar -x -f {0} {1}'.format(pkg, ' '.join(files)) __salt__['cmd.run'](cmd, cwd=temp_dir, output_loglevel='quiet') # Find our identifiers for f in files: i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f)) if i: package_ids.extend(i) else: package_ids = _get_pkg_id_dir(pkg) finally: # Clean up __salt__['file.remove'](temp_dir) return package_ids def get_mpkg_ids(mpkg): ''' Attempt to get the package IDs from a mounted .mpkg file Args: mpkg (str): The location of the mounted mpkg file Returns: list: List of package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_mpkg_ids /dev/disk2 ''' mpkg = _quote(mpkg) package_infos = [] base_path = os.path.dirname(mpkg) # List all of the .pkg files cmd = 'find {0} -name *.pkg'.format(base_path) out = __salt__['cmd.run'](cmd, python_shell=True) pkg_files = out.split('\n') for p in pkg_files: package_infos.extend(get_pkg_id(p)) return package_infos def _get_pkg_id_from_pkginfo(pkginfo): # Find our identifiers pkginfo = _quote(pkginfo) cmd = 'cat {0} | grep -Eo \'identifier="[a-zA-Z.0-9\\-]*"\' | cut -c 13- | tr -d \'"\''.format(pkginfo) out = __salt__['cmd.run'](cmd, python_shell=True) if 'No such file' not in out: return out.split('\n') return [] def _get_pkg_id_dir(path): path = _quote(os.path.join(path, 'Contents/Info.plist')) cmd = '/usr/libexec/PlistBuddy -c "print :CFBundleIdentifier" {0}'.format(path) # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True out = __salt__['cmd.run'](cmd, python_shell=python_shell) if 'Does Not Exist' not in out: return [out] return []
saltstack/salt
salt/modules/macpackage.py
mount
python
def mount(dmg): ''' Attempt to mount a dmg file to a temporary location and return the location of the pkg file inside Args: dmg (str): The location of the dmg file to mount Returns: tuple: Tuple containing the results of the command along with the mount point CLI Example: .. code-block:: bash salt '*' macpackage.mount /tmp/software.dmg ''' temp_dir = __salt__['temp.dir'](prefix='dmg-') cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {0} "{1}"'.format(temp_dir, dmg) return __salt__['cmd.run'](cmd), temp_dir
Attempt to mount a dmg file to a temporary location and return the location of the pkg file inside Args: dmg (str): The location of the dmg file to mount Returns: tuple: Tuple containing the results of the command along with the mount point CLI Example: .. code-block:: bash salt '*' macpackage.mount /tmp/software.dmg
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macpackage.py#L138-L161
null
# -*- coding: utf-8 -*- ''' Install pkg, dmg and .app applications on macOS minions. ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import os import logging import shlex try: import pipes HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'macpackage' if hasattr(shlex, 'quote'): _quote = shlex.quote elif HAS_DEPS and hasattr(pipes, 'quote'): _quote = pipes.quote else: _quote = None def __virtual__(): ''' Only work on Mac OS ''' if salt.utils.platform.is_darwin() and _quote is not None: return __virtualname__ return False def install(pkg, target='LocalSystem', store=False, allow_untrusted=False): ''' Install a pkg file Args: pkg (str): The package to install target (str): The target in which to install the package to store (bool): Should the package be installed as if it was from the store? allow_untrusted (bool): Allow the installation of untrusted packages? Returns: dict: A dictionary containing the results of the installation CLI Example: .. code-block:: bash salt '*' macpackage.install test.pkg ''' if '*.' not in pkg: # If we use wildcards, we cannot use quotes pkg = _quote(pkg) target = _quote(target) cmd = 'installer -pkg {0} -target {1}'.format(pkg, target) if store: cmd += ' -store' if allow_untrusted: cmd += ' -allowUntrusted' # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True return __salt__['cmd.run_all'](cmd, python_shell=python_shell) def install_app(app, target='/Applications/'): ''' Install an app file by moving it into the specified Applications directory Args: app (str): The location of the .app file target (str): The target in which to install the package to Default is ''/Applications/'' Returns: str: The results of the rsync command CLI Example: .. code-block:: bash salt '*' macpackage.install_app /tmp/tmp.app /Applications/ ''' if target[-4:] != '.app': if app[-1:] == '/': base_app = os.path.basename(app[:-1]) else: base_app = os.path.basename(app) target = os.path.join(target, base_app) if not app[-1] == '/': app += '/' cmd = 'rsync -a --delete "{0}" "{1}"'.format(app, target) return __salt__['cmd.run'](cmd) def uninstall_app(app): ''' Uninstall an app file by removing it from the Applications directory Args: app (str): The location of the .app file Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' macpackage.uninstall_app /Applications/app.app ''' return __salt__['file.remove'](app) def unmount(mountpoint): ''' Attempt to unmount a dmg file from a temporary location Args: mountpoint (str): The location of the mount point Returns: str: The results of the hdutil detach command CLI Example: .. code-block:: bash salt '*' macpackage.unmount /dev/disk2 ''' cmd = 'hdiutil detach "{0}"'.format(mountpoint) return __salt__['cmd.run'](cmd) def installed_pkgs(): ''' Return the list of installed packages on the machine Returns: list: List of installed packages CLI Example: .. code-block:: bash salt '*' macpackage.installed_pkgs ''' cmd = 'pkgutil --pkgs' return __salt__['cmd.run'](cmd).split('\n') def get_pkg_id(pkg): ''' Attempt to get the package ID from a .pkg file Args: pkg (str): The location of the pkg file Returns: list: List of all of the package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_pkg_id /tmp/test.pkg ''' pkg = _quote(pkg) package_ids = [] # Create temp directory temp_dir = __salt__['temp.dir'](prefix='pkg-') try: # List all of the PackageInfo files cmd = 'xar -t -f {0} | grep PackageInfo'.format(pkg) out = __salt__['cmd.run'](cmd, python_shell=True, output_loglevel='quiet') files = out.split('\n') if 'Error opening' not in out: # Extract the PackageInfo files cmd = 'xar -x -f {0} {1}'.format(pkg, ' '.join(files)) __salt__['cmd.run'](cmd, cwd=temp_dir, output_loglevel='quiet') # Find our identifiers for f in files: i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f)) if i: package_ids.extend(i) else: package_ids = _get_pkg_id_dir(pkg) finally: # Clean up __salt__['file.remove'](temp_dir) return package_ids def get_mpkg_ids(mpkg): ''' Attempt to get the package IDs from a mounted .mpkg file Args: mpkg (str): The location of the mounted mpkg file Returns: list: List of package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_mpkg_ids /dev/disk2 ''' mpkg = _quote(mpkg) package_infos = [] base_path = os.path.dirname(mpkg) # List all of the .pkg files cmd = 'find {0} -name *.pkg'.format(base_path) out = __salt__['cmd.run'](cmd, python_shell=True) pkg_files = out.split('\n') for p in pkg_files: package_infos.extend(get_pkg_id(p)) return package_infos def _get_pkg_id_from_pkginfo(pkginfo): # Find our identifiers pkginfo = _quote(pkginfo) cmd = 'cat {0} | grep -Eo \'identifier="[a-zA-Z.0-9\\-]*"\' | cut -c 13- | tr -d \'"\''.format(pkginfo) out = __salt__['cmd.run'](cmd, python_shell=True) if 'No such file' not in out: return out.split('\n') return [] def _get_pkg_id_dir(path): path = _quote(os.path.join(path, 'Contents/Info.plist')) cmd = '/usr/libexec/PlistBuddy -c "print :CFBundleIdentifier" {0}'.format(path) # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True out = __salt__['cmd.run'](cmd, python_shell=python_shell) if 'Does Not Exist' not in out: return [out] return []
saltstack/salt
salt/modules/macpackage.py
get_pkg_id
python
def get_pkg_id(pkg): ''' Attempt to get the package ID from a .pkg file Args: pkg (str): The location of the pkg file Returns: list: List of all of the package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_pkg_id /tmp/test.pkg ''' pkg = _quote(pkg) package_ids = [] # Create temp directory temp_dir = __salt__['temp.dir'](prefix='pkg-') try: # List all of the PackageInfo files cmd = 'xar -t -f {0} | grep PackageInfo'.format(pkg) out = __salt__['cmd.run'](cmd, python_shell=True, output_loglevel='quiet') files = out.split('\n') if 'Error opening' not in out: # Extract the PackageInfo files cmd = 'xar -x -f {0} {1}'.format(pkg, ' '.join(files)) __salt__['cmd.run'](cmd, cwd=temp_dir, output_loglevel='quiet') # Find our identifiers for f in files: i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f)) if i: package_ids.extend(i) else: package_ids = _get_pkg_id_dir(pkg) finally: # Clean up __salt__['file.remove'](temp_dir) return package_ids
Attempt to get the package ID from a .pkg file Args: pkg (str): The location of the pkg file Returns: list: List of all of the package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_pkg_id /tmp/test.pkg
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macpackage.py#L205-L250
[ "def _get_pkg_id_from_pkginfo(pkginfo):\n # Find our identifiers\n pkginfo = _quote(pkginfo)\n cmd = 'cat {0} | grep -Eo \\'identifier=\"[a-zA-Z.0-9\\\\-]*\"\\' | cut -c 13- | tr -d \\'\"\\''.format(pkginfo)\n out = __salt__['cmd.run'](cmd, python_shell=True)\n\n if 'No such file' not in out:\n return out.split('\\n')\n\n return []\n", "def _get_pkg_id_dir(path):\n path = _quote(os.path.join(path, 'Contents/Info.plist'))\n cmd = '/usr/libexec/PlistBuddy -c \"print :CFBundleIdentifier\" {0}'.format(path)\n\n # We can only use wildcards in python_shell which is\n # sent by the macpackage state\n python_shell = False\n if '*.' in cmd:\n python_shell = True\n\n out = __salt__['cmd.run'](cmd, python_shell=python_shell)\n\n if 'Does Not Exist' not in out:\n return [out]\n\n return []\n" ]
# -*- coding: utf-8 -*- ''' Install pkg, dmg and .app applications on macOS minions. ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import os import logging import shlex try: import pipes HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'macpackage' if hasattr(shlex, 'quote'): _quote = shlex.quote elif HAS_DEPS and hasattr(pipes, 'quote'): _quote = pipes.quote else: _quote = None def __virtual__(): ''' Only work on Mac OS ''' if salt.utils.platform.is_darwin() and _quote is not None: return __virtualname__ return False def install(pkg, target='LocalSystem', store=False, allow_untrusted=False): ''' Install a pkg file Args: pkg (str): The package to install target (str): The target in which to install the package to store (bool): Should the package be installed as if it was from the store? allow_untrusted (bool): Allow the installation of untrusted packages? Returns: dict: A dictionary containing the results of the installation CLI Example: .. code-block:: bash salt '*' macpackage.install test.pkg ''' if '*.' not in pkg: # If we use wildcards, we cannot use quotes pkg = _quote(pkg) target = _quote(target) cmd = 'installer -pkg {0} -target {1}'.format(pkg, target) if store: cmd += ' -store' if allow_untrusted: cmd += ' -allowUntrusted' # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True return __salt__['cmd.run_all'](cmd, python_shell=python_shell) def install_app(app, target='/Applications/'): ''' Install an app file by moving it into the specified Applications directory Args: app (str): The location of the .app file target (str): The target in which to install the package to Default is ''/Applications/'' Returns: str: The results of the rsync command CLI Example: .. code-block:: bash salt '*' macpackage.install_app /tmp/tmp.app /Applications/ ''' if target[-4:] != '.app': if app[-1:] == '/': base_app = os.path.basename(app[:-1]) else: base_app = os.path.basename(app) target = os.path.join(target, base_app) if not app[-1] == '/': app += '/' cmd = 'rsync -a --delete "{0}" "{1}"'.format(app, target) return __salt__['cmd.run'](cmd) def uninstall_app(app): ''' Uninstall an app file by removing it from the Applications directory Args: app (str): The location of the .app file Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' macpackage.uninstall_app /Applications/app.app ''' return __salt__['file.remove'](app) def mount(dmg): ''' Attempt to mount a dmg file to a temporary location and return the location of the pkg file inside Args: dmg (str): The location of the dmg file to mount Returns: tuple: Tuple containing the results of the command along with the mount point CLI Example: .. code-block:: bash salt '*' macpackage.mount /tmp/software.dmg ''' temp_dir = __salt__['temp.dir'](prefix='dmg-') cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {0} "{1}"'.format(temp_dir, dmg) return __salt__['cmd.run'](cmd), temp_dir def unmount(mountpoint): ''' Attempt to unmount a dmg file from a temporary location Args: mountpoint (str): The location of the mount point Returns: str: The results of the hdutil detach command CLI Example: .. code-block:: bash salt '*' macpackage.unmount /dev/disk2 ''' cmd = 'hdiutil detach "{0}"'.format(mountpoint) return __salt__['cmd.run'](cmd) def installed_pkgs(): ''' Return the list of installed packages on the machine Returns: list: List of installed packages CLI Example: .. code-block:: bash salt '*' macpackage.installed_pkgs ''' cmd = 'pkgutil --pkgs' return __salt__['cmd.run'](cmd).split('\n') def get_mpkg_ids(mpkg): ''' Attempt to get the package IDs from a mounted .mpkg file Args: mpkg (str): The location of the mounted mpkg file Returns: list: List of package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_mpkg_ids /dev/disk2 ''' mpkg = _quote(mpkg) package_infos = [] base_path = os.path.dirname(mpkg) # List all of the .pkg files cmd = 'find {0} -name *.pkg'.format(base_path) out = __salt__['cmd.run'](cmd, python_shell=True) pkg_files = out.split('\n') for p in pkg_files: package_infos.extend(get_pkg_id(p)) return package_infos def _get_pkg_id_from_pkginfo(pkginfo): # Find our identifiers pkginfo = _quote(pkginfo) cmd = 'cat {0} | grep -Eo \'identifier="[a-zA-Z.0-9\\-]*"\' | cut -c 13- | tr -d \'"\''.format(pkginfo) out = __salt__['cmd.run'](cmd, python_shell=True) if 'No such file' not in out: return out.split('\n') return [] def _get_pkg_id_dir(path): path = _quote(os.path.join(path, 'Contents/Info.plist')) cmd = '/usr/libexec/PlistBuddy -c "print :CFBundleIdentifier" {0}'.format(path) # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True out = __salt__['cmd.run'](cmd, python_shell=python_shell) if 'Does Not Exist' not in out: return [out] return []
saltstack/salt
salt/modules/macpackage.py
get_mpkg_ids
python
def get_mpkg_ids(mpkg): ''' Attempt to get the package IDs from a mounted .mpkg file Args: mpkg (str): The location of the mounted mpkg file Returns: list: List of package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_mpkg_ids /dev/disk2 ''' mpkg = _quote(mpkg) package_infos = [] base_path = os.path.dirname(mpkg) # List all of the .pkg files cmd = 'find {0} -name *.pkg'.format(base_path) out = __salt__['cmd.run'](cmd, python_shell=True) pkg_files = out.split('\n') for p in pkg_files: package_infos.extend(get_pkg_id(p)) return package_infos
Attempt to get the package IDs from a mounted .mpkg file Args: mpkg (str): The location of the mounted mpkg file Returns: list: List of package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_mpkg_ids /dev/disk2
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macpackage.py#L253-L281
[ "def get_pkg_id(pkg):\n '''\n Attempt to get the package ID from a .pkg file\n\n Args:\n pkg (str): The location of the pkg file\n\n Returns:\n list: List of all of the package IDs\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' macpackage.get_pkg_id /tmp/test.pkg\n '''\n pkg = _quote(pkg)\n package_ids = []\n\n # Create temp directory\n temp_dir = __salt__['temp.dir'](prefix='pkg-')\n\n try:\n # List all of the PackageInfo files\n cmd = 'xar -t -f {0} | grep PackageInfo'.format(pkg)\n out = __salt__['cmd.run'](cmd, python_shell=True, output_loglevel='quiet')\n files = out.split('\\n')\n\n if 'Error opening' not in out:\n # Extract the PackageInfo files\n cmd = 'xar -x -f {0} {1}'.format(pkg, ' '.join(files))\n __salt__['cmd.run'](cmd, cwd=temp_dir, output_loglevel='quiet')\n\n # Find our identifiers\n for f in files:\n i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f))\n if i:\n package_ids.extend(i)\n else:\n package_ids = _get_pkg_id_dir(pkg)\n\n finally:\n # Clean up\n __salt__['file.remove'](temp_dir)\n\n return package_ids\n" ]
# -*- coding: utf-8 -*- ''' Install pkg, dmg and .app applications on macOS minions. ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import os import logging import shlex try: import pipes HAS_DEPS = True except ImportError: HAS_DEPS = False # Import Salt libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'macpackage' if hasattr(shlex, 'quote'): _quote = shlex.quote elif HAS_DEPS and hasattr(pipes, 'quote'): _quote = pipes.quote else: _quote = None def __virtual__(): ''' Only work on Mac OS ''' if salt.utils.platform.is_darwin() and _quote is not None: return __virtualname__ return False def install(pkg, target='LocalSystem', store=False, allow_untrusted=False): ''' Install a pkg file Args: pkg (str): The package to install target (str): The target in which to install the package to store (bool): Should the package be installed as if it was from the store? allow_untrusted (bool): Allow the installation of untrusted packages? Returns: dict: A dictionary containing the results of the installation CLI Example: .. code-block:: bash salt '*' macpackage.install test.pkg ''' if '*.' not in pkg: # If we use wildcards, we cannot use quotes pkg = _quote(pkg) target = _quote(target) cmd = 'installer -pkg {0} -target {1}'.format(pkg, target) if store: cmd += ' -store' if allow_untrusted: cmd += ' -allowUntrusted' # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True return __salt__['cmd.run_all'](cmd, python_shell=python_shell) def install_app(app, target='/Applications/'): ''' Install an app file by moving it into the specified Applications directory Args: app (str): The location of the .app file target (str): The target in which to install the package to Default is ''/Applications/'' Returns: str: The results of the rsync command CLI Example: .. code-block:: bash salt '*' macpackage.install_app /tmp/tmp.app /Applications/ ''' if target[-4:] != '.app': if app[-1:] == '/': base_app = os.path.basename(app[:-1]) else: base_app = os.path.basename(app) target = os.path.join(target, base_app) if not app[-1] == '/': app += '/' cmd = 'rsync -a --delete "{0}" "{1}"'.format(app, target) return __salt__['cmd.run'](cmd) def uninstall_app(app): ''' Uninstall an app file by removing it from the Applications directory Args: app (str): The location of the .app file Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' macpackage.uninstall_app /Applications/app.app ''' return __salt__['file.remove'](app) def mount(dmg): ''' Attempt to mount a dmg file to a temporary location and return the location of the pkg file inside Args: dmg (str): The location of the dmg file to mount Returns: tuple: Tuple containing the results of the command along with the mount point CLI Example: .. code-block:: bash salt '*' macpackage.mount /tmp/software.dmg ''' temp_dir = __salt__['temp.dir'](prefix='dmg-') cmd = 'hdiutil attach -readonly -nobrowse -mountpoint {0} "{1}"'.format(temp_dir, dmg) return __salt__['cmd.run'](cmd), temp_dir def unmount(mountpoint): ''' Attempt to unmount a dmg file from a temporary location Args: mountpoint (str): The location of the mount point Returns: str: The results of the hdutil detach command CLI Example: .. code-block:: bash salt '*' macpackage.unmount /dev/disk2 ''' cmd = 'hdiutil detach "{0}"'.format(mountpoint) return __salt__['cmd.run'](cmd) def installed_pkgs(): ''' Return the list of installed packages on the machine Returns: list: List of installed packages CLI Example: .. code-block:: bash salt '*' macpackage.installed_pkgs ''' cmd = 'pkgutil --pkgs' return __salt__['cmd.run'](cmd).split('\n') def get_pkg_id(pkg): ''' Attempt to get the package ID from a .pkg file Args: pkg (str): The location of the pkg file Returns: list: List of all of the package IDs CLI Example: .. code-block:: bash salt '*' macpackage.get_pkg_id /tmp/test.pkg ''' pkg = _quote(pkg) package_ids = [] # Create temp directory temp_dir = __salt__['temp.dir'](prefix='pkg-') try: # List all of the PackageInfo files cmd = 'xar -t -f {0} | grep PackageInfo'.format(pkg) out = __salt__['cmd.run'](cmd, python_shell=True, output_loglevel='quiet') files = out.split('\n') if 'Error opening' not in out: # Extract the PackageInfo files cmd = 'xar -x -f {0} {1}'.format(pkg, ' '.join(files)) __salt__['cmd.run'](cmd, cwd=temp_dir, output_loglevel='quiet') # Find our identifiers for f in files: i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f)) if i: package_ids.extend(i) else: package_ids = _get_pkg_id_dir(pkg) finally: # Clean up __salt__['file.remove'](temp_dir) return package_ids def _get_pkg_id_from_pkginfo(pkginfo): # Find our identifiers pkginfo = _quote(pkginfo) cmd = 'cat {0} | grep -Eo \'identifier="[a-zA-Z.0-9\\-]*"\' | cut -c 13- | tr -d \'"\''.format(pkginfo) out = __salt__['cmd.run'](cmd, python_shell=True) if 'No such file' not in out: return out.split('\n') return [] def _get_pkg_id_dir(path): path = _quote(os.path.join(path, 'Contents/Info.plist')) cmd = '/usr/libexec/PlistBuddy -c "print :CFBundleIdentifier" {0}'.format(path) # We can only use wildcards in python_shell which is # sent by the macpackage state python_shell = False if '*.' in cmd: python_shell = True out = __salt__['cmd.run'](cmd, python_shell=python_shell) if 'Does Not Exist' not in out: return [out] return []
saltstack/salt
salt/modules/apkpkg.py
refresh_db
python
def refresh_db(**kwargs): ''' Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' ret = {} cmd = ['apk', 'update'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] == 0: errors = [] ret = True else: errors = [call['stdout']] ret = False if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret
Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apkpkg.py#L86-L117
null
# -*- coding: utf-8 -*- ''' Support for apk .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. .. versionadded: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import copy import logging # Import salt libs import salt.utils.data import salt.utils.itertools from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'pkg' def __virtual__(): ''' Confirm this module is running on an Alpine Linux distribution ''' if __grains__.get('os_family', False) == 'Alpine': return __virtualname__ return (False, "Module apk only works on Alpine Linux based systems") #def autoremove(list_only=False, purge=False): # return 'Not available' #def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def upgrade_available(name): # return 'Not available' #def version_cmp(pkg1, pkg2, ignore_epoch=False): # return 'Not available' #def list_repos(): # return 'Not available' #def get_repo(repo, **kwargs): # return 'Not available' #def del_repo(repo, **kwargs): # return 'Not available' #def del_repo_key(name=None, **kwargs): # return 'Not available' #def mod_repo(repo, saltenv='base', **kwargs): # return 'Not available' #def expand_repo_def(**kwargs): # return 'Not available' #def get_selections(pattern=None, state=None): # return 'Not available' #def set_selections(path=None, selection=None, clear=False, saltenv='base'): # return 'Not available' #def info_installed(*names): # return 'Not available' def version(*names, **kwargs): ''' Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2> <package3> ... ''' return __salt__['pkg_resource.version'](*names, **kwargs) def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs versions_as_list=True ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret cmd = ['apk', 'info', '-v'] ret = {} out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret def latest_version(*names, **kwargs): ''' Return the latest version of the named package available for upgrade or installation. If more than one package name is specified, a dict of name/version pairs is returned. If the latest version of a given package is already installed, an empty string will be returned for that package. CLI Example: .. code-block:: bash salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package1> <package2> <package3> ... ''' refresh = salt.utils.data.is_true(kwargs.pop('refresh', True)) if not names: return '' ret = {} for name in names: ret[name] = '' pkgs = list_pkgs() # Refresh before looking for the latest version available if refresh: refresh_db() # Upgrade check cmd = ['apk', 'upgrade', '-s'] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') if name in names: ret[name] = newversion except (ValueError, IndexError): pass # If version is empty, package may not be installed for pkg in ret: if not ret[pkg]: installed = pkgs.get(pkg) cmd = ['apk', 'search', pkg] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) if pkg == pkg_name: if installed == pkg_version: ret[pkg] = '' else: ret[pkg] = pkg_version except ValueError: pass # Return a string if only one package name passed if len(names) == 1: return ret[names[0]] return ret # TODO: Support specific version installation def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): ''' Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to refresh the package database before installing. Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' sources A list of IPK packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. Dependencies are automatically resolved and marked as auto-installed. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]' install_recommends Whether to install the packages marked as recommended. Default is True. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' refreshdb = salt.utils.data.is_true(refresh) pkg_to_install = [] old = list_pkgs() if name and not (pkgs or sources): if ',' in name: pkg_to_install = name.split(',') else: pkg_to_install = [name] if pkgs: # We don't support installing specific version for now # so transform the dict in list ignoring version provided pkgs = [ next(iter(p)) for p in pkgs if isinstance(p, dict) ] pkg_to_install.extend(pkgs) if not pkg_to_install: return {} if refreshdb: refresh_db() cmd = ['apk', 'add'] # Switch in update mode if a package is already installed for _pkg in pkg_to_install: if old.get(_pkg): cmd.append('-u') break cmd.extend(pkg_to_install) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def purge(name=None, pkgs=None, **kwargs): ''' Alias to remove ''' return remove(name=name, pkgs=pkgs, purge=True) def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' old = list_pkgs() pkg_to_remove = [] if name: if ',' in name: pkg_to_remove = name.split(',') else: pkg_to_remove = [name] if pkgs: pkg_to_remove.extend(pkgs) if not pkg_to_remove: return {} if purge: cmd = ['apk', 'del', '--purge'] else: cmd = ['apk', 'del'] cmd.extend(pkg_to_remove) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret def upgrade(name=None, pkgs=None, refresh=True, **kwargs): ''' Upgrades all packages via ``apk upgrade`` or a specific package if name or pkgs is specified. Name is ignored if pkgs is specified Returns a dict containing the changes. {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade ''' ret = {'changes': {}, 'result': True, 'comment': '', } if salt.utils.data.is_true(refresh): refresh_db() old = list_pkgs() pkg_to_upgrade = [] if name and not pkgs: if ',' in name: pkg_to_upgrade = name.split(',') else: pkg_to_upgrade = [name] if pkgs: pkg_to_upgrade.extend(pkgs) if pkg_to_upgrade: cmd = ['apk', 'add', '-u'] cmd.extend(pkg_to_upgrade) else: cmd = ['apk', 'upgrade'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False, redirect_stderr=True) if call['retcode'] != 0: ret['result'] = False if call['stdout']: ret['comment'] = call['stdout'] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = ['apk', 'upgrade', '-s'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError(comment) else: out = call['stdout'] for line in out.splitlines(): if 'Upgrading' in line: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') ret[name] = newversion return ret def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' return file_dict(*packages) def file_dict(*packages, **kwargs): ''' List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' errors = [] ret = {} cmd_files = ['apk', 'info', '-L'] if not packages: return 'Package name should be provided' for package in packages: files = [] cmd = cmd_files[:] cmd.append(package) out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) for line in out['stdout'].splitlines(): if line.endswith('contains:'): continue else: files.append(line) if files: ret[package] = files return {'errors': errors, 'packages': ret} def owner(*paths, **kwargs): ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Example: salt '*' pkg.owns /usr/bin/apachectl salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename ''' if not paths: return 'You must provide a path' ret = {} cmd_search = ['apk', 'info', '-W'] for path in paths: cmd = cmd_search[:] cmd.append(path) output = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) if output: if 'ERROR:' in output: ret[path] = 'Could not find owner package' else: ret[path] = output.split('by ')[1].strip() else: ret[path] = 'Error running {0}'.format(cmd) return ret
saltstack/salt
salt/modules/apkpkg.py
list_pkgs
python
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs versions_as_list=True ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret cmd = ['apk', 'info', '-v'] ret = {} out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret
List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs versions_as_list=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apkpkg.py#L120-L159
[ "def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n", "def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n" ]
# -*- coding: utf-8 -*- ''' Support for apk .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. .. versionadded: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import copy import logging # Import salt libs import salt.utils.data import salt.utils.itertools from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'pkg' def __virtual__(): ''' Confirm this module is running on an Alpine Linux distribution ''' if __grains__.get('os_family', False) == 'Alpine': return __virtualname__ return (False, "Module apk only works on Alpine Linux based systems") #def autoremove(list_only=False, purge=False): # return 'Not available' #def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def upgrade_available(name): # return 'Not available' #def version_cmp(pkg1, pkg2, ignore_epoch=False): # return 'Not available' #def list_repos(): # return 'Not available' #def get_repo(repo, **kwargs): # return 'Not available' #def del_repo(repo, **kwargs): # return 'Not available' #def del_repo_key(name=None, **kwargs): # return 'Not available' #def mod_repo(repo, saltenv='base', **kwargs): # return 'Not available' #def expand_repo_def(**kwargs): # return 'Not available' #def get_selections(pattern=None, state=None): # return 'Not available' #def set_selections(path=None, selection=None, clear=False, saltenv='base'): # return 'Not available' #def info_installed(*names): # return 'Not available' def version(*names, **kwargs): ''' Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2> <package3> ... ''' return __salt__['pkg_resource.version'](*names, **kwargs) def refresh_db(**kwargs): ''' Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' ret = {} cmd = ['apk', 'update'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] == 0: errors = [] ret = True else: errors = [call['stdout']] ret = False if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def latest_version(*names, **kwargs): ''' Return the latest version of the named package available for upgrade or installation. If more than one package name is specified, a dict of name/version pairs is returned. If the latest version of a given package is already installed, an empty string will be returned for that package. CLI Example: .. code-block:: bash salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package1> <package2> <package3> ... ''' refresh = salt.utils.data.is_true(kwargs.pop('refresh', True)) if not names: return '' ret = {} for name in names: ret[name] = '' pkgs = list_pkgs() # Refresh before looking for the latest version available if refresh: refresh_db() # Upgrade check cmd = ['apk', 'upgrade', '-s'] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') if name in names: ret[name] = newversion except (ValueError, IndexError): pass # If version is empty, package may not be installed for pkg in ret: if not ret[pkg]: installed = pkgs.get(pkg) cmd = ['apk', 'search', pkg] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) if pkg == pkg_name: if installed == pkg_version: ret[pkg] = '' else: ret[pkg] = pkg_version except ValueError: pass # Return a string if only one package name passed if len(names) == 1: return ret[names[0]] return ret # TODO: Support specific version installation def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): ''' Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to refresh the package database before installing. Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' sources A list of IPK packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. Dependencies are automatically resolved and marked as auto-installed. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]' install_recommends Whether to install the packages marked as recommended. Default is True. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' refreshdb = salt.utils.data.is_true(refresh) pkg_to_install = [] old = list_pkgs() if name and not (pkgs or sources): if ',' in name: pkg_to_install = name.split(',') else: pkg_to_install = [name] if pkgs: # We don't support installing specific version for now # so transform the dict in list ignoring version provided pkgs = [ next(iter(p)) for p in pkgs if isinstance(p, dict) ] pkg_to_install.extend(pkgs) if not pkg_to_install: return {} if refreshdb: refresh_db() cmd = ['apk', 'add'] # Switch in update mode if a package is already installed for _pkg in pkg_to_install: if old.get(_pkg): cmd.append('-u') break cmd.extend(pkg_to_install) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def purge(name=None, pkgs=None, **kwargs): ''' Alias to remove ''' return remove(name=name, pkgs=pkgs, purge=True) def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' old = list_pkgs() pkg_to_remove = [] if name: if ',' in name: pkg_to_remove = name.split(',') else: pkg_to_remove = [name] if pkgs: pkg_to_remove.extend(pkgs) if not pkg_to_remove: return {} if purge: cmd = ['apk', 'del', '--purge'] else: cmd = ['apk', 'del'] cmd.extend(pkg_to_remove) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret def upgrade(name=None, pkgs=None, refresh=True, **kwargs): ''' Upgrades all packages via ``apk upgrade`` or a specific package if name or pkgs is specified. Name is ignored if pkgs is specified Returns a dict containing the changes. {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade ''' ret = {'changes': {}, 'result': True, 'comment': '', } if salt.utils.data.is_true(refresh): refresh_db() old = list_pkgs() pkg_to_upgrade = [] if name and not pkgs: if ',' in name: pkg_to_upgrade = name.split(',') else: pkg_to_upgrade = [name] if pkgs: pkg_to_upgrade.extend(pkgs) if pkg_to_upgrade: cmd = ['apk', 'add', '-u'] cmd.extend(pkg_to_upgrade) else: cmd = ['apk', 'upgrade'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False, redirect_stderr=True) if call['retcode'] != 0: ret['result'] = False if call['stdout']: ret['comment'] = call['stdout'] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = ['apk', 'upgrade', '-s'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError(comment) else: out = call['stdout'] for line in out.splitlines(): if 'Upgrading' in line: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') ret[name] = newversion return ret def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' return file_dict(*packages) def file_dict(*packages, **kwargs): ''' List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' errors = [] ret = {} cmd_files = ['apk', 'info', '-L'] if not packages: return 'Package name should be provided' for package in packages: files = [] cmd = cmd_files[:] cmd.append(package) out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) for line in out['stdout'].splitlines(): if line.endswith('contains:'): continue else: files.append(line) if files: ret[package] = files return {'errors': errors, 'packages': ret} def owner(*paths, **kwargs): ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Example: salt '*' pkg.owns /usr/bin/apachectl salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename ''' if not paths: return 'You must provide a path' ret = {} cmd_search = ['apk', 'info', '-W'] for path in paths: cmd = cmd_search[:] cmd.append(path) output = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) if output: if 'ERROR:' in output: ret[path] = 'Could not find owner package' else: ret[path] = output.split('by ')[1].strip() else: ret[path] = 'Error running {0}'.format(cmd) return ret
saltstack/salt
salt/modules/apkpkg.py
install
python
def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): ''' Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to refresh the package database before installing. Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' sources A list of IPK packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. Dependencies are automatically resolved and marked as auto-installed. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]' install_recommends Whether to install the packages marked as recommended. Default is True. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' refreshdb = salt.utils.data.is_true(refresh) pkg_to_install = [] old = list_pkgs() if name and not (pkgs or sources): if ',' in name: pkg_to_install = name.split(',') else: pkg_to_install = [name] if pkgs: # We don't support installing specific version for now # so transform the dict in list ignoring version provided pkgs = [ next(iter(p)) for p in pkgs if isinstance(p, dict) ] pkg_to_install.extend(pkgs) if not pkg_to_install: return {} if refreshdb: refresh_db() cmd = ['apk', 'add'] # Switch in update mode if a package is already installed for _pkg in pkg_to_install: if old.get(_pkg): cmd.append('-u') break cmd.extend(pkg_to_install) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret
Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to refresh the package database before installing. Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' sources A list of IPK packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. Dependencies are automatically resolved and marked as auto-installed. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]' install_recommends Whether to install the packages marked as recommended. Default is True. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apkpkg.py#L235-L349
[ "def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n", "def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n cmd = ['apk', 'info', '-v']\n ret = {}\n out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)\n for line in salt.utils.itertools.split(out, '\\n'):\n pkg_version = '-'.join(line.split('-')[-2:])\n pkg_name = '-'.join(line.split('-')[:-2])\n __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n", "def refresh_db(**kwargs):\n '''\n Updates the package list\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n ret = {}\n cmd = ['apk', 'update']\n call = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False)\n if call['retcode'] == 0:\n errors = []\n ret = True\n else:\n errors = [call['stdout']]\n ret = False\n\n if errors:\n raise CommandExecutionError(\n 'Problem encountered installing package(s)',\n info={'errors': errors, 'changes': ret}\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for apk .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. .. versionadded: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import copy import logging # Import salt libs import salt.utils.data import salt.utils.itertools from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'pkg' def __virtual__(): ''' Confirm this module is running on an Alpine Linux distribution ''' if __grains__.get('os_family', False) == 'Alpine': return __virtualname__ return (False, "Module apk only works on Alpine Linux based systems") #def autoremove(list_only=False, purge=False): # return 'Not available' #def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def upgrade_available(name): # return 'Not available' #def version_cmp(pkg1, pkg2, ignore_epoch=False): # return 'Not available' #def list_repos(): # return 'Not available' #def get_repo(repo, **kwargs): # return 'Not available' #def del_repo(repo, **kwargs): # return 'Not available' #def del_repo_key(name=None, **kwargs): # return 'Not available' #def mod_repo(repo, saltenv='base', **kwargs): # return 'Not available' #def expand_repo_def(**kwargs): # return 'Not available' #def get_selections(pattern=None, state=None): # return 'Not available' #def set_selections(path=None, selection=None, clear=False, saltenv='base'): # return 'Not available' #def info_installed(*names): # return 'Not available' def version(*names, **kwargs): ''' Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2> <package3> ... ''' return __salt__['pkg_resource.version'](*names, **kwargs) def refresh_db(**kwargs): ''' Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' ret = {} cmd = ['apk', 'update'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] == 0: errors = [] ret = True else: errors = [call['stdout']] ret = False if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs versions_as_list=True ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret cmd = ['apk', 'info', '-v'] ret = {} out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret def latest_version(*names, **kwargs): ''' Return the latest version of the named package available for upgrade or installation. If more than one package name is specified, a dict of name/version pairs is returned. If the latest version of a given package is already installed, an empty string will be returned for that package. CLI Example: .. code-block:: bash salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package1> <package2> <package3> ... ''' refresh = salt.utils.data.is_true(kwargs.pop('refresh', True)) if not names: return '' ret = {} for name in names: ret[name] = '' pkgs = list_pkgs() # Refresh before looking for the latest version available if refresh: refresh_db() # Upgrade check cmd = ['apk', 'upgrade', '-s'] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') if name in names: ret[name] = newversion except (ValueError, IndexError): pass # If version is empty, package may not be installed for pkg in ret: if not ret[pkg]: installed = pkgs.get(pkg) cmd = ['apk', 'search', pkg] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) if pkg == pkg_name: if installed == pkg_version: ret[pkg] = '' else: ret[pkg] = pkg_version except ValueError: pass # Return a string if only one package name passed if len(names) == 1: return ret[names[0]] return ret # TODO: Support specific version installation def purge(name=None, pkgs=None, **kwargs): ''' Alias to remove ''' return remove(name=name, pkgs=pkgs, purge=True) def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' old = list_pkgs() pkg_to_remove = [] if name: if ',' in name: pkg_to_remove = name.split(',') else: pkg_to_remove = [name] if pkgs: pkg_to_remove.extend(pkgs) if not pkg_to_remove: return {} if purge: cmd = ['apk', 'del', '--purge'] else: cmd = ['apk', 'del'] cmd.extend(pkg_to_remove) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret def upgrade(name=None, pkgs=None, refresh=True, **kwargs): ''' Upgrades all packages via ``apk upgrade`` or a specific package if name or pkgs is specified. Name is ignored if pkgs is specified Returns a dict containing the changes. {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade ''' ret = {'changes': {}, 'result': True, 'comment': '', } if salt.utils.data.is_true(refresh): refresh_db() old = list_pkgs() pkg_to_upgrade = [] if name and not pkgs: if ',' in name: pkg_to_upgrade = name.split(',') else: pkg_to_upgrade = [name] if pkgs: pkg_to_upgrade.extend(pkgs) if pkg_to_upgrade: cmd = ['apk', 'add', '-u'] cmd.extend(pkg_to_upgrade) else: cmd = ['apk', 'upgrade'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False, redirect_stderr=True) if call['retcode'] != 0: ret['result'] = False if call['stdout']: ret['comment'] = call['stdout'] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = ['apk', 'upgrade', '-s'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError(comment) else: out = call['stdout'] for line in out.splitlines(): if 'Upgrading' in line: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') ret[name] = newversion return ret def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' return file_dict(*packages) def file_dict(*packages, **kwargs): ''' List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' errors = [] ret = {} cmd_files = ['apk', 'info', '-L'] if not packages: return 'Package name should be provided' for package in packages: files = [] cmd = cmd_files[:] cmd.append(package) out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) for line in out['stdout'].splitlines(): if line.endswith('contains:'): continue else: files.append(line) if files: ret[package] = files return {'errors': errors, 'packages': ret} def owner(*paths, **kwargs): ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Example: salt '*' pkg.owns /usr/bin/apachectl salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename ''' if not paths: return 'You must provide a path' ret = {} cmd_search = ['apk', 'info', '-W'] for path in paths: cmd = cmd_search[:] cmd.append(path) output = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) if output: if 'ERROR:' in output: ret[path] = 'Could not find owner package' else: ret[path] = output.split('by ')[1].strip() else: ret[path] = 'Error running {0}'.format(cmd) return ret
saltstack/salt
salt/modules/apkpkg.py
remove
python
def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' old = list_pkgs() pkg_to_remove = [] if name: if ',' in name: pkg_to_remove = name.split(',') else: pkg_to_remove = [name] if pkgs: pkg_to_remove.extend(pkgs) if not pkg_to_remove: return {} if purge: cmd = ['apk', 'del', '--purge'] else: cmd = ['apk', 'del'] cmd.extend(pkg_to_remove) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret
Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apkpkg.py#L359-L425
[ "def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n cmd = ['apk', 'info', '-v']\n ret = {}\n out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)\n for line in salt.utils.itertools.split(out, '\\n'):\n pkg_version = '-'.join(line.split('-')[-2:])\n pkg_name = '-'.join(line.split('-')[:-2])\n __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for apk .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. .. versionadded: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import copy import logging # Import salt libs import salt.utils.data import salt.utils.itertools from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'pkg' def __virtual__(): ''' Confirm this module is running on an Alpine Linux distribution ''' if __grains__.get('os_family', False) == 'Alpine': return __virtualname__ return (False, "Module apk only works on Alpine Linux based systems") #def autoremove(list_only=False, purge=False): # return 'Not available' #def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def upgrade_available(name): # return 'Not available' #def version_cmp(pkg1, pkg2, ignore_epoch=False): # return 'Not available' #def list_repos(): # return 'Not available' #def get_repo(repo, **kwargs): # return 'Not available' #def del_repo(repo, **kwargs): # return 'Not available' #def del_repo_key(name=None, **kwargs): # return 'Not available' #def mod_repo(repo, saltenv='base', **kwargs): # return 'Not available' #def expand_repo_def(**kwargs): # return 'Not available' #def get_selections(pattern=None, state=None): # return 'Not available' #def set_selections(path=None, selection=None, clear=False, saltenv='base'): # return 'Not available' #def info_installed(*names): # return 'Not available' def version(*names, **kwargs): ''' Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2> <package3> ... ''' return __salt__['pkg_resource.version'](*names, **kwargs) def refresh_db(**kwargs): ''' Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' ret = {} cmd = ['apk', 'update'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] == 0: errors = [] ret = True else: errors = [call['stdout']] ret = False if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs versions_as_list=True ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret cmd = ['apk', 'info', '-v'] ret = {} out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret def latest_version(*names, **kwargs): ''' Return the latest version of the named package available for upgrade or installation. If more than one package name is specified, a dict of name/version pairs is returned. If the latest version of a given package is already installed, an empty string will be returned for that package. CLI Example: .. code-block:: bash salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package1> <package2> <package3> ... ''' refresh = salt.utils.data.is_true(kwargs.pop('refresh', True)) if not names: return '' ret = {} for name in names: ret[name] = '' pkgs = list_pkgs() # Refresh before looking for the latest version available if refresh: refresh_db() # Upgrade check cmd = ['apk', 'upgrade', '-s'] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') if name in names: ret[name] = newversion except (ValueError, IndexError): pass # If version is empty, package may not be installed for pkg in ret: if not ret[pkg]: installed = pkgs.get(pkg) cmd = ['apk', 'search', pkg] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) if pkg == pkg_name: if installed == pkg_version: ret[pkg] = '' else: ret[pkg] = pkg_version except ValueError: pass # Return a string if only one package name passed if len(names) == 1: return ret[names[0]] return ret # TODO: Support specific version installation def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): ''' Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to refresh the package database before installing. Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' sources A list of IPK packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. Dependencies are automatically resolved and marked as auto-installed. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]' install_recommends Whether to install the packages marked as recommended. Default is True. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' refreshdb = salt.utils.data.is_true(refresh) pkg_to_install = [] old = list_pkgs() if name and not (pkgs or sources): if ',' in name: pkg_to_install = name.split(',') else: pkg_to_install = [name] if pkgs: # We don't support installing specific version for now # so transform the dict in list ignoring version provided pkgs = [ next(iter(p)) for p in pkgs if isinstance(p, dict) ] pkg_to_install.extend(pkgs) if not pkg_to_install: return {} if refreshdb: refresh_db() cmd = ['apk', 'add'] # Switch in update mode if a package is already installed for _pkg in pkg_to_install: if old.get(_pkg): cmd.append('-u') break cmd.extend(pkg_to_install) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def purge(name=None, pkgs=None, **kwargs): ''' Alias to remove ''' return remove(name=name, pkgs=pkgs, purge=True) def upgrade(name=None, pkgs=None, refresh=True, **kwargs): ''' Upgrades all packages via ``apk upgrade`` or a specific package if name or pkgs is specified. Name is ignored if pkgs is specified Returns a dict containing the changes. {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade ''' ret = {'changes': {}, 'result': True, 'comment': '', } if salt.utils.data.is_true(refresh): refresh_db() old = list_pkgs() pkg_to_upgrade = [] if name and not pkgs: if ',' in name: pkg_to_upgrade = name.split(',') else: pkg_to_upgrade = [name] if pkgs: pkg_to_upgrade.extend(pkgs) if pkg_to_upgrade: cmd = ['apk', 'add', '-u'] cmd.extend(pkg_to_upgrade) else: cmd = ['apk', 'upgrade'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False, redirect_stderr=True) if call['retcode'] != 0: ret['result'] = False if call['stdout']: ret['comment'] = call['stdout'] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = ['apk', 'upgrade', '-s'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError(comment) else: out = call['stdout'] for line in out.splitlines(): if 'Upgrading' in line: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') ret[name] = newversion return ret def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' return file_dict(*packages) def file_dict(*packages, **kwargs): ''' List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' errors = [] ret = {} cmd_files = ['apk', 'info', '-L'] if not packages: return 'Package name should be provided' for package in packages: files = [] cmd = cmd_files[:] cmd.append(package) out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) for line in out['stdout'].splitlines(): if line.endswith('contains:'): continue else: files.append(line) if files: ret[package] = files return {'errors': errors, 'packages': ret} def owner(*paths, **kwargs): ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Example: salt '*' pkg.owns /usr/bin/apachectl salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename ''' if not paths: return 'You must provide a path' ret = {} cmd_search = ['apk', 'info', '-W'] for path in paths: cmd = cmd_search[:] cmd.append(path) output = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) if output: if 'ERROR:' in output: ret[path] = 'Could not find owner package' else: ret[path] = output.split('by ')[1].strip() else: ret[path] = 'Error running {0}'.format(cmd) return ret
saltstack/salt
salt/modules/apkpkg.py
upgrade
python
def upgrade(name=None, pkgs=None, refresh=True, **kwargs): ''' Upgrades all packages via ``apk upgrade`` or a specific package if name or pkgs is specified. Name is ignored if pkgs is specified Returns a dict containing the changes. {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade ''' ret = {'changes': {}, 'result': True, 'comment': '', } if salt.utils.data.is_true(refresh): refresh_db() old = list_pkgs() pkg_to_upgrade = [] if name and not pkgs: if ',' in name: pkg_to_upgrade = name.split(',') else: pkg_to_upgrade = [name] if pkgs: pkg_to_upgrade.extend(pkgs) if pkg_to_upgrade: cmd = ['apk', 'add', '-u'] cmd.extend(pkg_to_upgrade) else: cmd = ['apk', 'upgrade'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False, redirect_stderr=True) if call['retcode'] != 0: ret['result'] = False if call['stdout']: ret['comment'] = call['stdout'] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret
Upgrades all packages via ``apk upgrade`` or a specific package if name or pkgs is specified. Name is ignored if pkgs is specified Returns a dict containing the changes. {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apkpkg.py#L428-L485
[ "def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n", "def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n cmd = ['apk', 'info', '-v']\n ret = {}\n out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)\n for line in salt.utils.itertools.split(out, '\\n'):\n pkg_version = '-'.join(line.split('-')[-2:])\n pkg_name = '-'.join(line.split('-')[:-2])\n __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n", "def refresh_db(**kwargs):\n '''\n Updates the package list\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n ret = {}\n cmd = ['apk', 'update']\n call = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False)\n if call['retcode'] == 0:\n errors = []\n ret = True\n else:\n errors = [call['stdout']]\n ret = False\n\n if errors:\n raise CommandExecutionError(\n 'Problem encountered installing package(s)',\n info={'errors': errors, 'changes': ret}\n )\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Support for apk .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. .. versionadded: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import copy import logging # Import salt libs import salt.utils.data import salt.utils.itertools from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'pkg' def __virtual__(): ''' Confirm this module is running on an Alpine Linux distribution ''' if __grains__.get('os_family', False) == 'Alpine': return __virtualname__ return (False, "Module apk only works on Alpine Linux based systems") #def autoremove(list_only=False, purge=False): # return 'Not available' #def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def upgrade_available(name): # return 'Not available' #def version_cmp(pkg1, pkg2, ignore_epoch=False): # return 'Not available' #def list_repos(): # return 'Not available' #def get_repo(repo, **kwargs): # return 'Not available' #def del_repo(repo, **kwargs): # return 'Not available' #def del_repo_key(name=None, **kwargs): # return 'Not available' #def mod_repo(repo, saltenv='base', **kwargs): # return 'Not available' #def expand_repo_def(**kwargs): # return 'Not available' #def get_selections(pattern=None, state=None): # return 'Not available' #def set_selections(path=None, selection=None, clear=False, saltenv='base'): # return 'Not available' #def info_installed(*names): # return 'Not available' def version(*names, **kwargs): ''' Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2> <package3> ... ''' return __salt__['pkg_resource.version'](*names, **kwargs) def refresh_db(**kwargs): ''' Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' ret = {} cmd = ['apk', 'update'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] == 0: errors = [] ret = True else: errors = [call['stdout']] ret = False if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs versions_as_list=True ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret cmd = ['apk', 'info', '-v'] ret = {} out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret def latest_version(*names, **kwargs): ''' Return the latest version of the named package available for upgrade or installation. If more than one package name is specified, a dict of name/version pairs is returned. If the latest version of a given package is already installed, an empty string will be returned for that package. CLI Example: .. code-block:: bash salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package1> <package2> <package3> ... ''' refresh = salt.utils.data.is_true(kwargs.pop('refresh', True)) if not names: return '' ret = {} for name in names: ret[name] = '' pkgs = list_pkgs() # Refresh before looking for the latest version available if refresh: refresh_db() # Upgrade check cmd = ['apk', 'upgrade', '-s'] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') if name in names: ret[name] = newversion except (ValueError, IndexError): pass # If version is empty, package may not be installed for pkg in ret: if not ret[pkg]: installed = pkgs.get(pkg) cmd = ['apk', 'search', pkg] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) if pkg == pkg_name: if installed == pkg_version: ret[pkg] = '' else: ret[pkg] = pkg_version except ValueError: pass # Return a string if only one package name passed if len(names) == 1: return ret[names[0]] return ret # TODO: Support specific version installation def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): ''' Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to refresh the package database before installing. Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' sources A list of IPK packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. Dependencies are automatically resolved and marked as auto-installed. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]' install_recommends Whether to install the packages marked as recommended. Default is True. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' refreshdb = salt.utils.data.is_true(refresh) pkg_to_install = [] old = list_pkgs() if name and not (pkgs or sources): if ',' in name: pkg_to_install = name.split(',') else: pkg_to_install = [name] if pkgs: # We don't support installing specific version for now # so transform the dict in list ignoring version provided pkgs = [ next(iter(p)) for p in pkgs if isinstance(p, dict) ] pkg_to_install.extend(pkgs) if not pkg_to_install: return {} if refreshdb: refresh_db() cmd = ['apk', 'add'] # Switch in update mode if a package is already installed for _pkg in pkg_to_install: if old.get(_pkg): cmd.append('-u') break cmd.extend(pkg_to_install) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def purge(name=None, pkgs=None, **kwargs): ''' Alias to remove ''' return remove(name=name, pkgs=pkgs, purge=True) def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' old = list_pkgs() pkg_to_remove = [] if name: if ',' in name: pkg_to_remove = name.split(',') else: pkg_to_remove = [name] if pkgs: pkg_to_remove.extend(pkgs) if not pkg_to_remove: return {} if purge: cmd = ['apk', 'del', '--purge'] else: cmd = ['apk', 'del'] cmd.extend(pkg_to_remove) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = ['apk', 'upgrade', '-s'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError(comment) else: out = call['stdout'] for line in out.splitlines(): if 'Upgrading' in line: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') ret[name] = newversion return ret def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' return file_dict(*packages) def file_dict(*packages, **kwargs): ''' List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' errors = [] ret = {} cmd_files = ['apk', 'info', '-L'] if not packages: return 'Package name should be provided' for package in packages: files = [] cmd = cmd_files[:] cmd.append(package) out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) for line in out['stdout'].splitlines(): if line.endswith('contains:'): continue else: files.append(line) if files: ret[package] = files return {'errors': errors, 'packages': ret} def owner(*paths, **kwargs): ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Example: salt '*' pkg.owns /usr/bin/apachectl salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename ''' if not paths: return 'You must provide a path' ret = {} cmd_search = ['apk', 'info', '-W'] for path in paths: cmd = cmd_search[:] cmd.append(path) output = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) if output: if 'ERROR:' in output: ret[path] = 'Could not find owner package' else: ret[path] = output.split('by ')[1].strip() else: ret[path] = 'Error running {0}'.format(cmd) return ret
saltstack/salt
salt/modules/apkpkg.py
file_dict
python
def file_dict(*packages, **kwargs): ''' List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' errors = [] ret = {} cmd_files = ['apk', 'info', '-L'] if not packages: return 'Package name should be provided' for package in packages: files = [] cmd = cmd_files[:] cmd.append(package) out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) for line in out['stdout'].splitlines(): if line.endswith('contains:'): continue else: files.append(line) if files: ret[package] = files return {'errors': errors, 'packages': ret}
List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apkpkg.py#L544-L580
null
# -*- coding: utf-8 -*- ''' Support for apk .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. .. versionadded: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import copy import logging # Import salt libs import salt.utils.data import salt.utils.itertools from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'pkg' def __virtual__(): ''' Confirm this module is running on an Alpine Linux distribution ''' if __grains__.get('os_family', False) == 'Alpine': return __virtualname__ return (False, "Module apk only works on Alpine Linux based systems") #def autoremove(list_only=False, purge=False): # return 'Not available' #def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def upgrade_available(name): # return 'Not available' #def version_cmp(pkg1, pkg2, ignore_epoch=False): # return 'Not available' #def list_repos(): # return 'Not available' #def get_repo(repo, **kwargs): # return 'Not available' #def del_repo(repo, **kwargs): # return 'Not available' #def del_repo_key(name=None, **kwargs): # return 'Not available' #def mod_repo(repo, saltenv='base', **kwargs): # return 'Not available' #def expand_repo_def(**kwargs): # return 'Not available' #def get_selections(pattern=None, state=None): # return 'Not available' #def set_selections(path=None, selection=None, clear=False, saltenv='base'): # return 'Not available' #def info_installed(*names): # return 'Not available' def version(*names, **kwargs): ''' Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2> <package3> ... ''' return __salt__['pkg_resource.version'](*names, **kwargs) def refresh_db(**kwargs): ''' Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' ret = {} cmd = ['apk', 'update'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] == 0: errors = [] ret = True else: errors = [call['stdout']] ret = False if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs versions_as_list=True ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret cmd = ['apk', 'info', '-v'] ret = {} out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret def latest_version(*names, **kwargs): ''' Return the latest version of the named package available for upgrade or installation. If more than one package name is specified, a dict of name/version pairs is returned. If the latest version of a given package is already installed, an empty string will be returned for that package. CLI Example: .. code-block:: bash salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package1> <package2> <package3> ... ''' refresh = salt.utils.data.is_true(kwargs.pop('refresh', True)) if not names: return '' ret = {} for name in names: ret[name] = '' pkgs = list_pkgs() # Refresh before looking for the latest version available if refresh: refresh_db() # Upgrade check cmd = ['apk', 'upgrade', '-s'] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') if name in names: ret[name] = newversion except (ValueError, IndexError): pass # If version is empty, package may not be installed for pkg in ret: if not ret[pkg]: installed = pkgs.get(pkg) cmd = ['apk', 'search', pkg] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) if pkg == pkg_name: if installed == pkg_version: ret[pkg] = '' else: ret[pkg] = pkg_version except ValueError: pass # Return a string if only one package name passed if len(names) == 1: return ret[names[0]] return ret # TODO: Support specific version installation def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): ''' Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to refresh the package database before installing. Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' sources A list of IPK packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. Dependencies are automatically resolved and marked as auto-installed. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]' install_recommends Whether to install the packages marked as recommended. Default is True. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' refreshdb = salt.utils.data.is_true(refresh) pkg_to_install = [] old = list_pkgs() if name and not (pkgs or sources): if ',' in name: pkg_to_install = name.split(',') else: pkg_to_install = [name] if pkgs: # We don't support installing specific version for now # so transform the dict in list ignoring version provided pkgs = [ next(iter(p)) for p in pkgs if isinstance(p, dict) ] pkg_to_install.extend(pkgs) if not pkg_to_install: return {} if refreshdb: refresh_db() cmd = ['apk', 'add'] # Switch in update mode if a package is already installed for _pkg in pkg_to_install: if old.get(_pkg): cmd.append('-u') break cmd.extend(pkg_to_install) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def purge(name=None, pkgs=None, **kwargs): ''' Alias to remove ''' return remove(name=name, pkgs=pkgs, purge=True) def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' old = list_pkgs() pkg_to_remove = [] if name: if ',' in name: pkg_to_remove = name.split(',') else: pkg_to_remove = [name] if pkgs: pkg_to_remove.extend(pkgs) if not pkg_to_remove: return {} if purge: cmd = ['apk', 'del', '--purge'] else: cmd = ['apk', 'del'] cmd.extend(pkg_to_remove) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret def upgrade(name=None, pkgs=None, refresh=True, **kwargs): ''' Upgrades all packages via ``apk upgrade`` or a specific package if name or pkgs is specified. Name is ignored if pkgs is specified Returns a dict containing the changes. {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade ''' ret = {'changes': {}, 'result': True, 'comment': '', } if salt.utils.data.is_true(refresh): refresh_db() old = list_pkgs() pkg_to_upgrade = [] if name and not pkgs: if ',' in name: pkg_to_upgrade = name.split(',') else: pkg_to_upgrade = [name] if pkgs: pkg_to_upgrade.extend(pkgs) if pkg_to_upgrade: cmd = ['apk', 'add', '-u'] cmd.extend(pkg_to_upgrade) else: cmd = ['apk', 'upgrade'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False, redirect_stderr=True) if call['retcode'] != 0: ret['result'] = False if call['stdout']: ret['comment'] = call['stdout'] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = ['apk', 'upgrade', '-s'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError(comment) else: out = call['stdout'] for line in out.splitlines(): if 'Upgrading' in line: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') ret[name] = newversion return ret def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' return file_dict(*packages) def owner(*paths, **kwargs): ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Example: salt '*' pkg.owns /usr/bin/apachectl salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename ''' if not paths: return 'You must provide a path' ret = {} cmd_search = ['apk', 'info', '-W'] for path in paths: cmd = cmd_search[:] cmd.append(path) output = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) if output: if 'ERROR:' in output: ret[path] = 'Could not find owner package' else: ret[path] = output.split('by ')[1].strip() else: ret[path] = 'Error running {0}'.format(cmd) return ret
saltstack/salt
salt/modules/apkpkg.py
owner
python
def owner(*paths, **kwargs): ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Example: salt '*' pkg.owns /usr/bin/apachectl salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename ''' if not paths: return 'You must provide a path' ret = {} cmd_search = ['apk', 'info', '-W'] for path in paths: cmd = cmd_search[:] cmd.append(path) output = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) if output: if 'ERROR:' in output: ret[path] = 'Could not find owner package' else: ret[path] = output.split('by ')[1].strip() else: ret[path] = 'Error running {0}'.format(cmd) return ret
Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not owned by a package, or is not present on the minion, then an empty string will be returned for that path. CLI Example: salt '*' pkg.owns /usr/bin/apachectl salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apkpkg.py#L583-L617
null
# -*- coding: utf-8 -*- ''' Support for apk .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. .. versionadded: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import copy import logging # Import salt libs import salt.utils.data import salt.utils.itertools from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'pkg' def __virtual__(): ''' Confirm this module is running on an Alpine Linux distribution ''' if __grains__.get('os_family', False) == 'Alpine': return __virtualname__ return (False, "Module apk only works on Alpine Linux based systems") #def autoremove(list_only=False, purge=False): # return 'Not available' #def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 # return 'Not available' #def upgrade_available(name): # return 'Not available' #def version_cmp(pkg1, pkg2, ignore_epoch=False): # return 'Not available' #def list_repos(): # return 'Not available' #def get_repo(repo, **kwargs): # return 'Not available' #def del_repo(repo, **kwargs): # return 'Not available' #def del_repo_key(name=None, **kwargs): # return 'Not available' #def mod_repo(repo, saltenv='base', **kwargs): # return 'Not available' #def expand_repo_def(**kwargs): # return 'Not available' #def get_selections(pattern=None, state=None): # return 'Not available' #def set_selections(path=None, selection=None, clear=False, saltenv='base'): # return 'Not available' #def info_installed(*names): # return 'Not available' def version(*names, **kwargs): ''' Returns a string representing the package version or an empty string if not installed. If more than one package name is specified, a dict of name/version pairs is returned. CLI Example: .. code-block:: bash salt '*' pkg.version <package name> salt '*' pkg.version <package1> <package2> <package3> ... ''' return __salt__['pkg_resource.version'](*names, **kwargs) def refresh_db(**kwargs): ''' Updates the package list - ``True``: Database updated successfully - ``False``: Problem updating database CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' ret = {} cmd = ['apk', 'update'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] == 0: errors = [] ret = True else: errors = [call['stdout']] ret = False if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs salt '*' pkg.list_pkgs versions_as_list=True ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret cmd = ['apk', 'info', '-v'] ret = {} out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret def latest_version(*names, **kwargs): ''' Return the latest version of the named package available for upgrade or installation. If more than one package name is specified, a dict of name/version pairs is returned. If the latest version of a given package is already installed, an empty string will be returned for that package. CLI Example: .. code-block:: bash salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package name> salt '*' pkg.latest_version <package1> <package2> <package3> ... ''' refresh = salt.utils.data.is_true(kwargs.pop('refresh', True)) if not names: return '' ret = {} for name in names: ret[name] = '' pkgs = list_pkgs() # Refresh before looking for the latest version available if refresh: refresh_db() # Upgrade check cmd = ['apk', 'upgrade', '-s'] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') if name in names: ret[name] = newversion except (ValueError, IndexError): pass # If version is empty, package may not be installed for pkg in ret: if not ret[pkg]: installed = pkgs.get(pkg) cmd = ['apk', 'search', pkg] out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False) for line in salt.utils.itertools.split(out, '\n'): try: pkg_version = '-'.join(line.split('-')[-2:]) pkg_name = '-'.join(line.split('-')[:-2]) if pkg == pkg_name: if installed == pkg_version: ret[pkg] = '' else: ret[pkg] = pkg_version except ValueError: pass # Return a string if only one package name passed if len(names) == 1: return ret[names[0]] return ret # TODO: Support specific version installation def install(name=None, refresh=False, pkgs=None, sources=None, **kwargs): ''' Install the passed package, add refresh=True to update the apk database. name The name of the package to be installed. Note that this parameter is ignored if either "pkgs" or "sources" is passed. Additionally, please note that this option can only be used to install packages from a software repository. To install a package file manually, use the "sources" option. CLI Example: .. code-block:: bash salt '*' pkg.install <package name> refresh Whether or not to refresh the package database before installing. Multiple Package Installation Options: pkgs A list of packages to install from a software repository. Must be passed as a python list. CLI Example: .. code-block:: bash salt '*' pkg.install pkgs='["foo", "bar"]' sources A list of IPK packages to install. Must be passed as a list of dicts, with the keys being package names, and the values being the source URI or local path to the package. Dependencies are automatically resolved and marked as auto-installed. CLI Example: .. code-block:: bash salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]' install_recommends Whether to install the packages marked as recommended. Default is True. Returns a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} ''' refreshdb = salt.utils.data.is_true(refresh) pkg_to_install = [] old = list_pkgs() if name and not (pkgs or sources): if ',' in name: pkg_to_install = name.split(',') else: pkg_to_install = [name] if pkgs: # We don't support installing specific version for now # so transform the dict in list ignoring version provided pkgs = [ next(iter(p)) for p in pkgs if isinstance(p, dict) ] pkg_to_install.extend(pkgs) if not pkg_to_install: return {} if refreshdb: refresh_db() cmd = ['apk', 'add'] # Switch in update mode if a package is already installed for _pkg in pkg_to_install: if old.get(_pkg): cmd.append('-u') break cmd.extend(pkg_to_install) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered installing package(s)', info={'errors': errors, 'changes': ret} ) return ret def purge(name=None, pkgs=None, **kwargs): ''' Alias to remove ''' return remove(name=name, pkgs=pkgs, purge=True) def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if this option is passed. Returns a dict containing the changes. CLI Example: .. code-block:: bash salt '*' pkg.remove <package name> salt '*' pkg.remove <package1>,<package2>,<package3> salt '*' pkg.remove pkgs='["foo", "bar"]' ''' old = list_pkgs() pkg_to_remove = [] if name: if ',' in name: pkg_to_remove = name.split(',') else: pkg_to_remove = [name] if pkgs: pkg_to_remove.extend(pkgs) if not pkg_to_remove: return {} if purge: cmd = ['apk', 'del', '--purge'] else: cmd = ['apk', 'del'] cmd.extend(pkg_to_remove) out = __salt__['cmd.run_all']( cmd, output_loglevel='trace', python_shell=False ) if out['retcode'] != 0 and out['stderr']: errors = [out['stderr']] else: errors = [] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret = salt.utils.data.compare_dicts(old, new) if errors: raise CommandExecutionError( 'Problem encountered removing package(s)', info={'errors': errors, 'changes': ret} ) return ret def upgrade(name=None, pkgs=None, refresh=True, **kwargs): ''' Upgrades all packages via ``apk upgrade`` or a specific package if name or pkgs is specified. Name is ignored if pkgs is specified Returns a dict containing the changes. {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkg.upgrade ''' ret = {'changes': {}, 'result': True, 'comment': '', } if salt.utils.data.is_true(refresh): refresh_db() old = list_pkgs() pkg_to_upgrade = [] if name and not pkgs: if ',' in name: pkg_to_upgrade = name.split(',') else: pkg_to_upgrade = [name] if pkgs: pkg_to_upgrade.extend(pkgs) if pkg_to_upgrade: cmd = ['apk', 'add', '-u'] cmd.extend(pkg_to_upgrade) else: cmd = ['apk', 'upgrade'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False, redirect_stderr=True) if call['retcode'] != 0: ret['result'] = False if call['stdout']: ret['comment'] = call['stdout'] __context__.pop('pkg.list_pkgs', None) new = list_pkgs() ret['changes'] = salt.utils.data.compare_dicts(old, new) return ret def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' ret = {} if salt.utils.data.is_true(refresh): refresh_db() cmd = ['apk', 'upgrade', '-s'] call = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError(comment) else: out = call['stdout'] for line in out.splitlines(): if 'Upgrading' in line: name = line.split(' ')[2] _oldversion = line.split(' ')[3].strip('(') newversion = line.split(' ')[5].strip(')') ret[name] = newversion return ret def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' return file_dict(*packages) def file_dict(*packages, **kwargs): ''' List the files that belong to a package, grouped by package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' pkg.file_list ''' errors = [] ret = {} cmd_files = ['apk', 'info', '-L'] if not packages: return 'Package name should be provided' for package in packages: files = [] cmd = cmd_files[:] cmd.append(package) out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False) for line in out['stdout'].splitlines(): if line.endswith('contains:'): continue else: files.append(line) if files: ret[package] = files return {'errors': errors, 'packages': ret}
saltstack/salt
salt/states/ini_manage.py
options_present
python
def options_present(name, sections=None, separator='=', strict=False): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_present: - separator: '=' - strict: True - sections: test: testkey: 'testval' secondoption: 'secondvalue' test1: testkey1: 'testval121' options present in file and not specified in sections dict will be untouched, unless `strict: True` flag is used changes dict will contain the list of changes made ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['comment'] = '' # pylint: disable=too-many-nested-blocks try: changes = {} if sections: options = {} for sname, sbody in sections.items(): if not isinstance(sbody, (dict, OrderedDict)): options.update({sname: sbody}) cur_ini = __salt__['ini.get_ini'](name, separator) original_top_level_opts = {} original_sections = {} for key, val in cur_ini.items(): if isinstance(val, (dict, OrderedDict)): original_sections.update({key: val}) else: original_top_level_opts.update({key: val}) if __opts__['test']: for option in options: if option in original_top_level_opts: if six.text_type(original_top_level_opts[option]) == six.text_type(options[option]): ret['comment'] += 'Unchanged key {0}.\n'.format(option) else: ret['comment'] += 'Changed key {0}.\n'.format(option) ret['result'] = None else: ret['comment'] += 'Changed key {0}.\n'.format(option) ret['result'] = None else: options_updated = __salt__['ini.set_option'](name, options, separator) changes.update(options_updated) if strict: for opt_to_remove in set(original_top_level_opts).difference(options): if __opts__['test']: ret['comment'] += 'Removed key {0}.\n'.format(opt_to_remove) ret['result'] = None else: __salt__['ini.remove_option'](name, None, opt_to_remove, separator) changes.update({opt_to_remove: {'before': original_top_level_opts[opt_to_remove], 'after': None}}) for section_name, section_body in [(sname, sbody) for sname, sbody in sections.items() if isinstance(sbody, (dict, OrderedDict))]: section_descr = ' in section ' + section_name if section_name else '' changes[section_name] = {} if strict: original = cur_ini.get(section_name, {}) for key_to_remove in set(original.keys()).difference(section_body.keys()): orig_value = original_sections.get(section_name, {}).get(key_to_remove, '#-#-') if __opts__['test']: ret['comment'] += 'Deleted key {0}{1}.\n'.format(key_to_remove, section_descr) ret['result'] = None else: __salt__['ini.remove_option'](name, section_name, key_to_remove, separator) changes[section_name].update({key_to_remove: ''}) changes[section_name].update({key_to_remove: {'before': orig_value, 'after': None}}) if __opts__['test']: for option in section_body: if six.text_type(section_body[option]) == \ six.text_type(original_sections.get(section_name, {}).get(option, '#-#-')): ret['comment'] += 'Unchanged key {0}{1}.\n'.format(option, section_descr) else: ret['comment'] += 'Changed key {0}{1}.\n'.format(option, section_descr) ret['result'] = None else: options_updated = __salt__['ini.set_option'](name, {section_name: section_body}, separator) if options_updated: changes[section_name].update(options_updated[section_name]) if not changes[section_name]: del changes[section_name] else: if not __opts__['test']: changes = __salt__['ini.set_option'](name, sections, separator) except (IOError, KeyError) as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret if 'error' in changes: ret['result'] = False ret['comment'] = 'Errors encountered. {0}'.format(changes['error']) ret['changes'] = {} else: for ciname, body in changes.items(): if body: ret['comment'] = 'Changes take effect' ret['changes'].update({ciname: changes[ciname]}) return ret
.. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_present: - separator: '=' - strict: True - sections: test: testkey: 'testval' secondoption: 'secondvalue' test1: testkey1: 'testval121' options present in file and not specified in sections dict will be untouched, unless `strict: True` flag is used changes dict will contain the list of changes made
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ini_manage.py#L30-L143
null
# -*- coding: utf-8 -*- ''' Manage ini files ================ :maintainer: <akilesh1597@gmail.com> :maturity: new :depends: re :platform: all ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs from salt.ext import six from salt.utils.odict import OrderedDict __virtualname__ = 'ini' def __virtual__(): ''' Only load if the ini module is available ''' return __virtualname__ if 'ini.set_option' in __salt__ else False def options_absent(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_absent: - separator: '=' - sections: test: - testkey - secondoption test1: - testkey1 options present in file and not specified in sections dict will be untouched changes dict will contain the list of changes made ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' for section in sections or {}: section_name = ' in section ' + section if section else '' try: cur_section = __salt__['ini.get_section'](name, section, separator) except IOError as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret except AttributeError: cur_section = section if isinstance(sections[section], (dict, OrderedDict)): for key in sections[section]: cur_value = cur_section.get(key) if not cur_value: ret['comment'] += 'Key {0}{1} does not exist.\n'.format(key, section_name) continue ret['comment'] += 'Deleted key {0}{1}.\n'.format(key, section_name) ret['result'] = None else: option = section if not __salt__['ini.get_option'](name, None, option, separator): ret['comment'] += 'Key {0} does not exist.\n'.format(option) continue ret['comment'] += 'Deleted key {0}.\n'.format(option) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret sections = sections or {} for section, keys in six.iteritems(sections): for key in keys: try: current_value = __salt__['ini.remove_option'](name, section, key, separator) except IOError as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret if not current_value: continue if section not in ret['changes']: ret['changes'].update({section: {}}) ret['changes'][section].update({key: current_value}) if not isinstance(sections[section], (dict, OrderedDict)): ret['changes'].update({section: current_value}) # break ret['comment'] = 'Changes take effect' return ret def sections_present(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_present: - separator: '=' - sections: - section_one - section_two This will only create empty sections. To also create options, use options_present state options present in file and not specified in sections will be deleted changes dict will contain the sections that changed ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' try: cur_ini = __salt__['ini.get_ini'](name, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret for section in sections or {}: if section in cur_ini: ret['comment'] += 'Section unchanged {0}.\n'.format(section) continue else: ret['comment'] += 'Created new section {0}.\n'.format(section) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret section_to_update = {} for section_name in sections or []: section_to_update.update({section_name: {}}) try: changes = __salt__['ini.set_option'](name, section_to_update, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret if 'error' in changes: ret['result'] = False ret['changes'] = 'Errors encountered {0}'.format(changes['error']) return ret ret['changes'] = changes ret['comment'] = 'Changes take effect' return ret def sections_absent(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_absent: - separator: '=' - sections: - test - test1 options present in file and not specified in sections will be deleted changes dict will contain the sections that changed ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' try: cur_ini = __salt__['ini.get_ini'](name, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret for section in sections or []: if section not in cur_ini: ret['comment'] += 'Section {0} does not exist.\n'.format(section) continue ret['comment'] += 'Deleted section {0}.\n'.format(section) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret for section in sections or []: try: cur_section = __salt__['ini.remove_section'](name, section, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret if not cur_section: continue ret['changes'][section] = cur_section ret['comment'] = 'Changes take effect' return ret
saltstack/salt
salt/states/ini_manage.py
options_absent
python
def options_absent(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_absent: - separator: '=' - sections: test: - testkey - secondoption test1: - testkey1 options present in file and not specified in sections dict will be untouched changes dict will contain the list of changes made ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' for section in sections or {}: section_name = ' in section ' + section if section else '' try: cur_section = __salt__['ini.get_section'](name, section, separator) except IOError as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret except AttributeError: cur_section = section if isinstance(sections[section], (dict, OrderedDict)): for key in sections[section]: cur_value = cur_section.get(key) if not cur_value: ret['comment'] += 'Key {0}{1} does not exist.\n'.format(key, section_name) continue ret['comment'] += 'Deleted key {0}{1}.\n'.format(key, section_name) ret['result'] = None else: option = section if not __salt__['ini.get_option'](name, None, option, separator): ret['comment'] += 'Key {0} does not exist.\n'.format(option) continue ret['comment'] += 'Deleted key {0}.\n'.format(option) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret sections = sections or {} for section, keys in six.iteritems(sections): for key in keys: try: current_value = __salt__['ini.remove_option'](name, section, key, separator) except IOError as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret if not current_value: continue if section not in ret['changes']: ret['changes'].update({section: {}}) ret['changes'][section].update({key: current_value}) if not isinstance(sections[section], (dict, OrderedDict)): ret['changes'].update({section: current_value}) # break ret['comment'] = 'Changes take effect' return ret
.. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_absent: - separator: '=' - sections: test: - testkey - secondoption test1: - testkey1 options present in file and not specified in sections dict will be untouched changes dict will contain the list of changes made
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ini_manage.py#L146-L220
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Manage ini files ================ :maintainer: <akilesh1597@gmail.com> :maturity: new :depends: re :platform: all ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs from salt.ext import six from salt.utils.odict import OrderedDict __virtualname__ = 'ini' def __virtual__(): ''' Only load if the ini module is available ''' return __virtualname__ if 'ini.set_option' in __salt__ else False def options_present(name, sections=None, separator='=', strict=False): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_present: - separator: '=' - strict: True - sections: test: testkey: 'testval' secondoption: 'secondvalue' test1: testkey1: 'testval121' options present in file and not specified in sections dict will be untouched, unless `strict: True` flag is used changes dict will contain the list of changes made ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['comment'] = '' # pylint: disable=too-many-nested-blocks try: changes = {} if sections: options = {} for sname, sbody in sections.items(): if not isinstance(sbody, (dict, OrderedDict)): options.update({sname: sbody}) cur_ini = __salt__['ini.get_ini'](name, separator) original_top_level_opts = {} original_sections = {} for key, val in cur_ini.items(): if isinstance(val, (dict, OrderedDict)): original_sections.update({key: val}) else: original_top_level_opts.update({key: val}) if __opts__['test']: for option in options: if option in original_top_level_opts: if six.text_type(original_top_level_opts[option]) == six.text_type(options[option]): ret['comment'] += 'Unchanged key {0}.\n'.format(option) else: ret['comment'] += 'Changed key {0}.\n'.format(option) ret['result'] = None else: ret['comment'] += 'Changed key {0}.\n'.format(option) ret['result'] = None else: options_updated = __salt__['ini.set_option'](name, options, separator) changes.update(options_updated) if strict: for opt_to_remove in set(original_top_level_opts).difference(options): if __opts__['test']: ret['comment'] += 'Removed key {0}.\n'.format(opt_to_remove) ret['result'] = None else: __salt__['ini.remove_option'](name, None, opt_to_remove, separator) changes.update({opt_to_remove: {'before': original_top_level_opts[opt_to_remove], 'after': None}}) for section_name, section_body in [(sname, sbody) for sname, sbody in sections.items() if isinstance(sbody, (dict, OrderedDict))]: section_descr = ' in section ' + section_name if section_name else '' changes[section_name] = {} if strict: original = cur_ini.get(section_name, {}) for key_to_remove in set(original.keys()).difference(section_body.keys()): orig_value = original_sections.get(section_name, {}).get(key_to_remove, '#-#-') if __opts__['test']: ret['comment'] += 'Deleted key {0}{1}.\n'.format(key_to_remove, section_descr) ret['result'] = None else: __salt__['ini.remove_option'](name, section_name, key_to_remove, separator) changes[section_name].update({key_to_remove: ''}) changes[section_name].update({key_to_remove: {'before': orig_value, 'after': None}}) if __opts__['test']: for option in section_body: if six.text_type(section_body[option]) == \ six.text_type(original_sections.get(section_name, {}).get(option, '#-#-')): ret['comment'] += 'Unchanged key {0}{1}.\n'.format(option, section_descr) else: ret['comment'] += 'Changed key {0}{1}.\n'.format(option, section_descr) ret['result'] = None else: options_updated = __salt__['ini.set_option'](name, {section_name: section_body}, separator) if options_updated: changes[section_name].update(options_updated[section_name]) if not changes[section_name]: del changes[section_name] else: if not __opts__['test']: changes = __salt__['ini.set_option'](name, sections, separator) except (IOError, KeyError) as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret if 'error' in changes: ret['result'] = False ret['comment'] = 'Errors encountered. {0}'.format(changes['error']) ret['changes'] = {} else: for ciname, body in changes.items(): if body: ret['comment'] = 'Changes take effect' ret['changes'].update({ciname: changes[ciname]}) return ret def sections_present(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_present: - separator: '=' - sections: - section_one - section_two This will only create empty sections. To also create options, use options_present state options present in file and not specified in sections will be deleted changes dict will contain the sections that changed ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' try: cur_ini = __salt__['ini.get_ini'](name, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret for section in sections or {}: if section in cur_ini: ret['comment'] += 'Section unchanged {0}.\n'.format(section) continue else: ret['comment'] += 'Created new section {0}.\n'.format(section) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret section_to_update = {} for section_name in sections or []: section_to_update.update({section_name: {}}) try: changes = __salt__['ini.set_option'](name, section_to_update, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret if 'error' in changes: ret['result'] = False ret['changes'] = 'Errors encountered {0}'.format(changes['error']) return ret ret['changes'] = changes ret['comment'] = 'Changes take effect' return ret def sections_absent(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_absent: - separator: '=' - sections: - test - test1 options present in file and not specified in sections will be deleted changes dict will contain the sections that changed ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' try: cur_ini = __salt__['ini.get_ini'](name, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret for section in sections or []: if section not in cur_ini: ret['comment'] += 'Section {0} does not exist.\n'.format(section) continue ret['comment'] += 'Deleted section {0}.\n'.format(section) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret for section in sections or []: try: cur_section = __salt__['ini.remove_section'](name, section, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret if not cur_section: continue ret['changes'][section] = cur_section ret['comment'] = 'Changes take effect' return ret
saltstack/salt
salt/states/ini_manage.py
sections_present
python
def sections_present(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_present: - separator: '=' - sections: - section_one - section_two This will only create empty sections. To also create options, use options_present state options present in file and not specified in sections will be deleted changes dict will contain the sections that changed ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' try: cur_ini = __salt__['ini.get_ini'](name, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret for section in sections or {}: if section in cur_ini: ret['comment'] += 'Section unchanged {0}.\n'.format(section) continue else: ret['comment'] += 'Created new section {0}.\n'.format(section) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret section_to_update = {} for section_name in sections or []: section_to_update.update({section_name: {}}) try: changes = __salt__['ini.set_option'](name, section_to_update, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret if 'error' in changes: ret['result'] = False ret['changes'] = 'Errors encountered {0}'.format(changes['error']) return ret ret['changes'] = changes ret['comment'] = 'Changes take effect' return ret
.. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_present: - separator: '=' - sections: - section_one - section_two This will only create empty sections. To also create options, use options_present state options present in file and not specified in sections will be deleted changes dict will contain the sections that changed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ini_manage.py#L223-L279
null
# -*- coding: utf-8 -*- ''' Manage ini files ================ :maintainer: <akilesh1597@gmail.com> :maturity: new :depends: re :platform: all ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs from salt.ext import six from salt.utils.odict import OrderedDict __virtualname__ = 'ini' def __virtual__(): ''' Only load if the ini module is available ''' return __virtualname__ if 'ini.set_option' in __salt__ else False def options_present(name, sections=None, separator='=', strict=False): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_present: - separator: '=' - strict: True - sections: test: testkey: 'testval' secondoption: 'secondvalue' test1: testkey1: 'testval121' options present in file and not specified in sections dict will be untouched, unless `strict: True` flag is used changes dict will contain the list of changes made ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['comment'] = '' # pylint: disable=too-many-nested-blocks try: changes = {} if sections: options = {} for sname, sbody in sections.items(): if not isinstance(sbody, (dict, OrderedDict)): options.update({sname: sbody}) cur_ini = __salt__['ini.get_ini'](name, separator) original_top_level_opts = {} original_sections = {} for key, val in cur_ini.items(): if isinstance(val, (dict, OrderedDict)): original_sections.update({key: val}) else: original_top_level_opts.update({key: val}) if __opts__['test']: for option in options: if option in original_top_level_opts: if six.text_type(original_top_level_opts[option]) == six.text_type(options[option]): ret['comment'] += 'Unchanged key {0}.\n'.format(option) else: ret['comment'] += 'Changed key {0}.\n'.format(option) ret['result'] = None else: ret['comment'] += 'Changed key {0}.\n'.format(option) ret['result'] = None else: options_updated = __salt__['ini.set_option'](name, options, separator) changes.update(options_updated) if strict: for opt_to_remove in set(original_top_level_opts).difference(options): if __opts__['test']: ret['comment'] += 'Removed key {0}.\n'.format(opt_to_remove) ret['result'] = None else: __salt__['ini.remove_option'](name, None, opt_to_remove, separator) changes.update({opt_to_remove: {'before': original_top_level_opts[opt_to_remove], 'after': None}}) for section_name, section_body in [(sname, sbody) for sname, sbody in sections.items() if isinstance(sbody, (dict, OrderedDict))]: section_descr = ' in section ' + section_name if section_name else '' changes[section_name] = {} if strict: original = cur_ini.get(section_name, {}) for key_to_remove in set(original.keys()).difference(section_body.keys()): orig_value = original_sections.get(section_name, {}).get(key_to_remove, '#-#-') if __opts__['test']: ret['comment'] += 'Deleted key {0}{1}.\n'.format(key_to_remove, section_descr) ret['result'] = None else: __salt__['ini.remove_option'](name, section_name, key_to_remove, separator) changes[section_name].update({key_to_remove: ''}) changes[section_name].update({key_to_remove: {'before': orig_value, 'after': None}}) if __opts__['test']: for option in section_body: if six.text_type(section_body[option]) == \ six.text_type(original_sections.get(section_name, {}).get(option, '#-#-')): ret['comment'] += 'Unchanged key {0}{1}.\n'.format(option, section_descr) else: ret['comment'] += 'Changed key {0}{1}.\n'.format(option, section_descr) ret['result'] = None else: options_updated = __salt__['ini.set_option'](name, {section_name: section_body}, separator) if options_updated: changes[section_name].update(options_updated[section_name]) if not changes[section_name]: del changes[section_name] else: if not __opts__['test']: changes = __salt__['ini.set_option'](name, sections, separator) except (IOError, KeyError) as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret if 'error' in changes: ret['result'] = False ret['comment'] = 'Errors encountered. {0}'.format(changes['error']) ret['changes'] = {} else: for ciname, body in changes.items(): if body: ret['comment'] = 'Changes take effect' ret['changes'].update({ciname: changes[ciname]}) return ret def options_absent(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_absent: - separator: '=' - sections: test: - testkey - secondoption test1: - testkey1 options present in file and not specified in sections dict will be untouched changes dict will contain the list of changes made ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' for section in sections or {}: section_name = ' in section ' + section if section else '' try: cur_section = __salt__['ini.get_section'](name, section, separator) except IOError as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret except AttributeError: cur_section = section if isinstance(sections[section], (dict, OrderedDict)): for key in sections[section]: cur_value = cur_section.get(key) if not cur_value: ret['comment'] += 'Key {0}{1} does not exist.\n'.format(key, section_name) continue ret['comment'] += 'Deleted key {0}{1}.\n'.format(key, section_name) ret['result'] = None else: option = section if not __salt__['ini.get_option'](name, None, option, separator): ret['comment'] += 'Key {0} does not exist.\n'.format(option) continue ret['comment'] += 'Deleted key {0}.\n'.format(option) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret sections = sections or {} for section, keys in six.iteritems(sections): for key in keys: try: current_value = __salt__['ini.remove_option'](name, section, key, separator) except IOError as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret if not current_value: continue if section not in ret['changes']: ret['changes'].update({section: {}}) ret['changes'][section].update({key: current_value}) if not isinstance(sections[section], (dict, OrderedDict)): ret['changes'].update({section: current_value}) # break ret['comment'] = 'Changes take effect' return ret def sections_absent(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_absent: - separator: '=' - sections: - test - test1 options present in file and not specified in sections will be deleted changes dict will contain the sections that changed ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' try: cur_ini = __salt__['ini.get_ini'](name, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret for section in sections or []: if section not in cur_ini: ret['comment'] += 'Section {0} does not exist.\n'.format(section) continue ret['comment'] += 'Deleted section {0}.\n'.format(section) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret for section in sections or []: try: cur_section = __salt__['ini.remove_section'](name, section, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret if not cur_section: continue ret['changes'][section] = cur_section ret['comment'] = 'Changes take effect' return ret
saltstack/salt
salt/states/ini_manage.py
sections_absent
python
def sections_absent(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_absent: - separator: '=' - sections: - test - test1 options present in file and not specified in sections will be deleted changes dict will contain the sections that changed ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' try: cur_ini = __salt__['ini.get_ini'](name, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret for section in sections or []: if section not in cur_ini: ret['comment'] += 'Section {0} does not exist.\n'.format(section) continue ret['comment'] += 'Deleted section {0}.\n'.format(section) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret for section in sections or []: try: cur_section = __salt__['ini.remove_section'](name, section, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret if not cur_section: continue ret['changes'][section] = cur_section ret['comment'] = 'Changes take effect' return ret
.. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_absent: - separator: '=' - sections: - test - test1 options present in file and not specified in sections will be deleted changes dict will contain the sections that changed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ini_manage.py#L282-L330
null
# -*- coding: utf-8 -*- ''' Manage ini files ================ :maintainer: <akilesh1597@gmail.com> :maturity: new :depends: re :platform: all ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs from salt.ext import six from salt.utils.odict import OrderedDict __virtualname__ = 'ini' def __virtual__(): ''' Only load if the ini module is available ''' return __virtualname__ if 'ini.set_option' in __salt__ else False def options_present(name, sections=None, separator='=', strict=False): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_present: - separator: '=' - strict: True - sections: test: testkey: 'testval' secondoption: 'secondvalue' test1: testkey1: 'testval121' options present in file and not specified in sections dict will be untouched, unless `strict: True` flag is used changes dict will contain the list of changes made ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['comment'] = '' # pylint: disable=too-many-nested-blocks try: changes = {} if sections: options = {} for sname, sbody in sections.items(): if not isinstance(sbody, (dict, OrderedDict)): options.update({sname: sbody}) cur_ini = __salt__['ini.get_ini'](name, separator) original_top_level_opts = {} original_sections = {} for key, val in cur_ini.items(): if isinstance(val, (dict, OrderedDict)): original_sections.update({key: val}) else: original_top_level_opts.update({key: val}) if __opts__['test']: for option in options: if option in original_top_level_opts: if six.text_type(original_top_level_opts[option]) == six.text_type(options[option]): ret['comment'] += 'Unchanged key {0}.\n'.format(option) else: ret['comment'] += 'Changed key {0}.\n'.format(option) ret['result'] = None else: ret['comment'] += 'Changed key {0}.\n'.format(option) ret['result'] = None else: options_updated = __salt__['ini.set_option'](name, options, separator) changes.update(options_updated) if strict: for opt_to_remove in set(original_top_level_opts).difference(options): if __opts__['test']: ret['comment'] += 'Removed key {0}.\n'.format(opt_to_remove) ret['result'] = None else: __salt__['ini.remove_option'](name, None, opt_to_remove, separator) changes.update({opt_to_remove: {'before': original_top_level_opts[opt_to_remove], 'after': None}}) for section_name, section_body in [(sname, sbody) for sname, sbody in sections.items() if isinstance(sbody, (dict, OrderedDict))]: section_descr = ' in section ' + section_name if section_name else '' changes[section_name] = {} if strict: original = cur_ini.get(section_name, {}) for key_to_remove in set(original.keys()).difference(section_body.keys()): orig_value = original_sections.get(section_name, {}).get(key_to_remove, '#-#-') if __opts__['test']: ret['comment'] += 'Deleted key {0}{1}.\n'.format(key_to_remove, section_descr) ret['result'] = None else: __salt__['ini.remove_option'](name, section_name, key_to_remove, separator) changes[section_name].update({key_to_remove: ''}) changes[section_name].update({key_to_remove: {'before': orig_value, 'after': None}}) if __opts__['test']: for option in section_body: if six.text_type(section_body[option]) == \ six.text_type(original_sections.get(section_name, {}).get(option, '#-#-')): ret['comment'] += 'Unchanged key {0}{1}.\n'.format(option, section_descr) else: ret['comment'] += 'Changed key {0}{1}.\n'.format(option, section_descr) ret['result'] = None else: options_updated = __salt__['ini.set_option'](name, {section_name: section_body}, separator) if options_updated: changes[section_name].update(options_updated[section_name]) if not changes[section_name]: del changes[section_name] else: if not __opts__['test']: changes = __salt__['ini.set_option'](name, sections, separator) except (IOError, KeyError) as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret if 'error' in changes: ret['result'] = False ret['comment'] = 'Errors encountered. {0}'.format(changes['error']) ret['changes'] = {} else: for ciname, body in changes.items(): if body: ret['comment'] = 'Changes take effect' ret['changes'].update({ciname: changes[ciname]}) return ret def options_absent(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.options_absent: - separator: '=' - sections: test: - testkey - secondoption test1: - testkey1 options present in file and not specified in sections dict will be untouched changes dict will contain the list of changes made ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' for section in sections or {}: section_name = ' in section ' + section if section else '' try: cur_section = __salt__['ini.get_section'](name, section, separator) except IOError as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret except AttributeError: cur_section = section if isinstance(sections[section], (dict, OrderedDict)): for key in sections[section]: cur_value = cur_section.get(key) if not cur_value: ret['comment'] += 'Key {0}{1} does not exist.\n'.format(key, section_name) continue ret['comment'] += 'Deleted key {0}{1}.\n'.format(key, section_name) ret['result'] = None else: option = section if not __salt__['ini.get_option'](name, None, option, separator): ret['comment'] += 'Key {0} does not exist.\n'.format(option) continue ret['comment'] += 'Deleted key {0}.\n'.format(option) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret sections = sections or {} for section, keys in six.iteritems(sections): for key in keys: try: current_value = __salt__['ini.remove_option'](name, section, key, separator) except IOError as err: ret['comment'] = "{0}".format(err) ret['result'] = False return ret if not current_value: continue if section not in ret['changes']: ret['changes'].update({section: {}}) ret['changes'][section].update({key: current_value}) if not isinstance(sections[section], (dict, OrderedDict)): ret['changes'].update({section: current_value}) # break ret['comment'] = 'Changes take effect' return ret def sections_present(name, sections=None, separator='='): ''' .. code-block:: yaml /home/saltminion/api-paste.ini: ini.sections_present: - separator: '=' - sections: - section_one - section_two This will only create empty sections. To also create options, use options_present state options present in file and not specified in sections will be deleted changes dict will contain the sections that changed ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'No anomaly detected' } if __opts__['test']: ret['result'] = True ret['comment'] = '' try: cur_ini = __salt__['ini.get_ini'](name, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret for section in sections or {}: if section in cur_ini: ret['comment'] += 'Section unchanged {0}.\n'.format(section) continue else: ret['comment'] += 'Created new section {0}.\n'.format(section) ret['result'] = None if ret['comment'] == '': ret['comment'] = 'No changes detected.' return ret section_to_update = {} for section_name in sections or []: section_to_update.update({section_name: {}}) try: changes = __salt__['ini.set_option'](name, section_to_update, separator) except IOError as err: ret['result'] = False ret['comment'] = "{0}".format(err) return ret if 'error' in changes: ret['result'] = False ret['changes'] = 'Errors encountered {0}'.format(changes['error']) return ret ret['changes'] = changes ret['comment'] = 'Changes take effect' return ret
saltstack/salt
salt/modules/pam.py
_parse
python
def _parse(contents=None, file_name=None): ''' Parse a standard pam config file ''' if contents: pass elif file_name and os.path.exists(file_name): with salt.utils.files.fopen(file_name, 'r') as ifile: contents = salt.utils.stringutils.to_unicode(ifile.read()) else: log.error('File "%s" does not exist', file_name) return False rules = [] for line in contents.splitlines(): if not line: continue if line.startswith('#'): continue control_flag = '' module = '' arguments = [] comps = line.split() interface = comps[0] position = 1 if comps[1].startswith('['): control_flag = comps[1].replace('[', '') for part in comps[2:]: position += 1 if part.endswith(']'): control_flag += ' {0}'.format(part.replace(']', '')) position += 1 break else: control_flag += ' {0}'.format(part) else: control_flag = comps[1] position += 1 module = comps[position] if len(comps) > position: position += 1 arguments = comps[position:] rules.append({'interface': interface, 'control_flag': control_flag, 'module': module, 'arguments': arguments}) return rules
Parse a standard pam config file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pam.py#L27-L73
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# -*- coding: utf-8 -*- ''' Support for pam ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os import logging # Import salt libs import salt.utils.files log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'pam' def __virtual__(): ''' Set the virtual name for the module ''' return __virtualname__ def read_file(file_name): ''' This is just a test function, to make sure parsing works CLI Example: .. code-block:: bash salt '*' pam.read_file /etc/pam.d/login ''' return _parse(file_name=file_name)
saltstack/salt
salt/modules/virt.py
__get_request_auth
python
def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0
Get libvirt.openAuth callback with username, password values overriding the configuration ones.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L137-L167
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
__get_conn
python
def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn
Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L170-L243
[ "def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n", "def __get_request_auth(username, password):\n '''\n Get libvirt.openAuth callback with username, password values overriding\n the configuration ones.\n '''\n\n # pylint: disable=unused-argument\n def __request_auth(credentials, user_data):\n '''Callback method passed to libvirt.openAuth().\n\n The credentials argument is a list of credentials that libvirt\n would like to request. An element of this list is a list containing\n 5 items (4 inputs, 1 output):\n - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME\n - a prompt to be displayed to the user\n - a challenge\n - a default result for the request\n - a place to store the actual result for the request\n\n The user_data argument is currently not set in the openAuth call.\n '''\n for credential in credentials:\n if credential[0] == libvirt.VIR_CRED_AUTHNAME:\n credential[4] = username if username else \\\n __salt__['config.get']('virt:connection:auth:username', credential[3])\n elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT:\n credential[4] = password if password else \\\n __salt__['config.get']('virt:connection:auth:password', credential[3])\n else:\n log.info('Unhandled credential type: %s', credential[0])\n return 0\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_domain
python
def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret
Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L246-L281
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_parse_qemu_img_info
python
def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0]
Parse qemu-img info JSON output into disk infos dictionary
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L284-L322
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_on_poweroff
python
def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else ''
Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L338-L349
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_on_reboot
python
def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else ''
Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L352-L363
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_on_crash
python
def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else ''
Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L366-L377
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_nics
python
def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics
Get domain network interfaces from a libvirt domain object.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L380-L413
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_graphics
python
def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out
Get domain graphics from a libvirt domain object.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L416-L429
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_disks
python
def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks
Get domain disks from a libvirt domain object.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L445-L490
[ "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n", "def _parse_qemu_img_info(info):\n '''\n Parse qemu-img info JSON output into disk infos dictionary\n '''\n raw_infos = salt.utils.json.loads(info)\n disks = []\n for disk_infos in raw_infos:\n disk = {\n 'file': disk_infos['filename'],\n 'file format': disk_infos['format'],\n 'disk size': disk_infos['actual-size'],\n 'virtual size': disk_infos['virtual-size'],\n 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None,\n }\n\n if 'full-backing-filename' in disk_infos.keys():\n disk['backing file'] = format(disk_infos['full-backing-filename'])\n\n if 'snapshots' in disk_infos.keys():\n disk['snapshots'] = [\n {\n 'id': snapshot['id'],\n 'tag': snapshot['name'],\n 'vmsize': snapshot['vm-state-size'],\n 'date': datetime.datetime.fromtimestamp(\n float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(),\n 'vmclock': datetime.datetime.utcfromtimestamp(\n float('{}.{}'.format(snapshot['vm-clock-sec'],\n snapshot['vm-clock-nsec']))).time().isoformat()\n } for snapshot in disk_infos['snapshots']]\n disks.append(disk)\n\n for disk in disks:\n if 'backing file' in disk.keys():\n candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']]\n if candidates:\n disk['backing file'] = candidates[0]\n\n return disks[0]\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_libvirt_creds
python
def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group}
Returns the user and group that the disk images should be owned by
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L493-L513
[ "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_migrate_command
python
def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource '
Returns the command shared by the different migration types
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L516-L532
[ "def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_gen_xml
python
def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context)
Generate the XML string to define a libvirt VM
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L545-L656
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_gen_vol_xml
python
def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context)
Generate the XML string to define a libvirt storage volume
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L659-L682
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_gen_net_xml
python
def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context)
Generate the XML string to define a libvirt network
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L685-L706
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_gen_pool_xml
python
def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context)
Generate the XML string to define a libvirt storage pool
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L709-L744
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_images_dir
python
def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir
Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L747-L764
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_zfs_image_create
python
def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path
Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L767-L833
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_qemu_image_create
python
def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest
Create the image file using specified disk_size or/and disk_image Return path to the created image file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L836-L925
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_disk_profile
python
def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist
Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L928-L1029
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs):\n '''\n Compute the disk file name and update it in the disk value.\n '''\n base_dir = disk.get('pool', None)\n if hypervisor in ['qemu', 'kvm', 'xen']:\n # Compute the base directory from the pool property. We may have either a path\n # or a libvirt pool name there.\n # If the pool is a known libvirt one with a target path, use it as target path\n if not base_dir:\n base_dir = _get_images_dir()\n else:\n if not base_dir.startswith('/'):\n # The pool seems not to be a path, lookup for pool infos\n infos = pool_info(base_dir, **kwargs)\n pool = infos[base_dir] if base_dir in infos else None\n if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'):\n raise CommandExecutionError(\n 'Unable to create new disk {0}, specified pool {1} does not exist '\n 'or is unsupported'.format(disk['name'], base_dir))\n base_dir = pool['target_path']\n if hypervisor == 'bhyve' and vm_name:\n disk['filename'] = '{0}.{1}'.format(vm_name, disk['name'])\n disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename'])\n elif vm_name:\n # Compute the filename and source file properties if possible\n disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format'])\n disk['source_file'] = os.path.join(base_dir, disk['filename'])\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_fill_disk_filename
python
def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename'])
Compute the disk file name and update it in the disk value.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1032-L1059
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_complete_nics
python
def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces
Complete missing data for network interfaces.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1062-L1136
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_nic_profile
python
def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac)
Compute NIC data based on profile
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1139-L1208
[ "def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n", "def _complete_nics(interfaces, hypervisor, dmac=None):\n '''\n Complete missing data for network interfaces.\n '''\n\n vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'}\n kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'}\n bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'}\n xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None}\n overlays = {\n 'xen': xen_overlay,\n 'kvm': kvm_overlay,\n 'qemu': kvm_overlay,\n 'vmware': vmware_overlay,\n 'bhyve': bhyve_overlay,\n }\n\n def _normalize_net_types(attributes):\n '''\n Guess which style of definition:\n\n bridge: br0\n\n or\n\n network: net0\n\n or\n\n type: network\n source: net0\n '''\n for type_ in ['bridge', 'network']:\n if type_ in attributes:\n attributes['type'] = type_\n # we want to discard the original key\n attributes['source'] = attributes.pop(type_)\n\n attributes['type'] = attributes.get('type', None)\n attributes['source'] = attributes.get('source', None)\n\n def _apply_default_overlay(attributes):\n '''\n Apply the default overlay to attributes\n '''\n for key, value in six.iteritems(overlays[hypervisor]):\n if key not in attributes or not attributes[key]:\n attributes[key] = value\n\n def _assign_mac(attributes, hypervisor):\n '''\n Compute mac address for NIC depending on hypervisor\n '''\n if dmac is not None:\n log.debug('Default MAC address is %s', dmac)\n if salt.utils.validate.net.mac(dmac):\n attributes['mac'] = dmac\n else:\n msg = 'Malformed MAC address: {0}'.format(dmac)\n raise CommandExecutionError(msg)\n else:\n if hypervisor in ['qemu', 'kvm']:\n attributes['mac'] = salt.utils.network.gen_mac(\n prefix='52:54:00')\n else:\n attributes['mac'] = salt.utils.network.gen_mac()\n\n for interface in interfaces:\n _normalize_net_types(interface)\n if interface.get('mac', None) is None:\n _assign_mac(interface, hypervisor)\n if hypervisor in overlays:\n _apply_default_overlay(interface)\n\n return interfaces\n", "def append_dict_profile_to_interface_list(profile_dict):\n '''\n Append dictionary profile data to interfaces list\n '''\n for interface_name, attributes in six.iteritems(profile_dict):\n attributes['name'] = interface_name\n interfaces.append(attributes)\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_get_merged_nics
python
def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp
Get network devices from the profile and merge uer defined ones with them.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1211-L1226
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
init
python
def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True
Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1229-L1723
[ "def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n", "def capabilities(**kwargs):\n '''\n Return the hypervisor connection capabilities.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n .. versionadded:: 2019.2.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' virt.capabilities\n '''\n conn = __get_conn(**kwargs)\n caps = ElementTree.fromstring(conn.getCapabilities())\n conn.close()\n\n return {\n 'host': _parse_caps_host(caps.find('host')),\n 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')]\n }\n", "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs):\n '''\n Gather the disk profile from the config or apply the default based\n on the active hypervisor\n\n This is the ``default`` profile for KVM/QEMU, which can be\n overridden in the configuration:\n\n .. code-block:: yaml\n\n virt:\n disk:\n default:\n - system:\n size: 8192\n format: qcow2\n model: virtio\n\n Example profile for KVM/QEMU with two disks, first is created\n from specified image, the second is empty:\n\n .. code-block:: yaml\n\n virt:\n disk:\n two_disks:\n - system:\n size: 8192\n format: qcow2\n model: virtio\n image: http://path/to/image.qcow2\n - lvm:\n size: 32768\n format: qcow2\n model: virtio\n\n The ``format`` and ``model`` parameters are optional, and will\n default to whatever is best suitable for the active hypervisor.\n '''\n default = [{'system':\n {'size': 8192}}]\n if hypervisor == 'vmware':\n overlay = {'format': 'vmdk',\n 'model': 'scsi',\n 'device': 'disk',\n 'pool': '[{0}] '.format(pool if pool else '0')}\n elif hypervisor in ['qemu', 'kvm']:\n overlay = {'format': 'qcow2',\n 'device': 'disk',\n 'model': 'virtio'}\n elif hypervisor in ['bhyve']:\n overlay = {'format': 'raw',\n 'device': 'disk',\n 'model': 'virtio',\n 'sparse_volume': False}\n elif hypervisor == 'xen':\n overlay = {'format': 'qcow2',\n 'device': 'disk',\n 'model': 'xen'}\n else:\n overlay = {}\n\n # Get the disks from the profile\n disklist = []\n if profile:\n disklist = copy.deepcopy(\n __salt__['config.get']('virt:disk', {}).get(profile, default))\n\n # Transform the list to remove one level of dictionnary and add the name as a property\n disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()]\n\n # Add the image to the first disk if there is one\n if image:\n # If image is specified in module arguments, then it will be used\n # for the first disk instead of the image from the disk profile\n log.debug('%s image from module arguments will be used for disk \"%s\"'\n ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', \"\"))\n disklist[0]['image'] = image\n\n # Merge with the user-provided disks definitions\n if disks:\n for udisk in disks:\n if 'name' in udisk:\n found = [disk for disk in disklist if udisk['name'] == disk['name']]\n if found:\n found[0].update(udisk)\n else:\n disklist.append(udisk)\n\n for disk in disklist:\n # Add the missing properties that have defaults\n for key, val in six.iteritems(overlay):\n if key not in disk:\n disk[key] = val\n\n # We may have an already computed source_file (i.e. image not created by our module)\n if 'source_file' in disk and disk['source_file']:\n disk['filename'] = os.path.basename(disk['source_file'])\n elif 'source_file' not in disk:\n _fill_disk_filename(vm_name, disk, hypervisor, **kwargs)\n\n return disklist\n", "def _gen_xml(name,\n cpu,\n mem,\n diskp,\n nicp,\n hypervisor,\n os_type,\n arch,\n graphics=None,\n loader=None,\n **kwargs):\n '''\n Generate the XML string to define a libvirt VM\n '''\n mem = int(mem) * 1024 # MB\n context = {\n 'hypervisor': hypervisor,\n 'name': name,\n 'cpu': six.text_type(cpu),\n 'mem': six.text_type(mem),\n }\n if hypervisor in ['qemu', 'kvm']:\n context['controller_model'] = False\n elif hypervisor == 'vmware':\n # TODO: make bus and model parameterized, this works for 64-bit Linux\n context['controller_model'] = 'lsilogic'\n\n # By default, set the graphics to listen to all addresses\n if graphics:\n if 'listen' not in graphics:\n graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'}\n elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address':\n graphics['listen']['address'] = '0.0.0.0'\n\n # Graphics of type 'none' means no graphics device at all\n if graphics.get('type', 'none') == 'none':\n graphics = None\n context['graphics'] = graphics\n\n if loader and 'path' not in loader:\n log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration')\n loader = None\n elif loader:\n loader_attributes = []\n for key, val in loader.items():\n if key == 'path':\n continue\n loader_attributes.append(\"{key}='{val}'\".format(key=key, val=val))\n loader['_attributes'] = ' '.join(loader_attributes)\n\n if 'boot_dev' in kwargs:\n context['boot_dev'] = []\n for dev in kwargs['boot_dev'].split():\n context['boot_dev'].append(dev)\n else:\n context['boot_dev'] = ['hd']\n\n context['loader'] = loader\n\n if os_type == 'xen':\n # Compute the Xen PV boot method\n if __grains__['os_family'] == 'Suse':\n context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen'\n context['boot_dev'] = []\n\n if 'serial_type' in kwargs:\n context['serial_type'] = kwargs['serial_type']\n if 'serial_type' in context and context['serial_type'] == 'tcp':\n if 'telnet_port' in kwargs:\n context['telnet_port'] = kwargs['telnet_port']\n else:\n context['telnet_port'] = 23023 # FIXME: use random unused port\n if 'serial_type' in context:\n if 'console' in kwargs:\n context['console'] = kwargs['console']\n else:\n context['console'] = True\n\n context['disks'] = []\n disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'}\n for i, disk in enumerate(diskp):\n prefix = disk_bus_map.get(disk['model'], 'sd')\n disk_context = {\n 'device': disk.get('device', 'disk'),\n 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]),\n 'disk_bus': disk['model'],\n 'type': disk['format'],\n 'index': six.text_type(i),\n }\n if 'source_file' and disk['source_file']:\n disk_context['source_file'] = disk['source_file']\n\n if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']:\n disk_context['address'] = False\n disk_context['driver'] = True\n elif hypervisor in ['esxi', 'vmware']:\n disk_context['address'] = True\n disk_context['driver'] = False\n context['disks'].append(disk_context)\n context['nics'] = nicp\n\n context['os_type'] = os_type\n context['arch'] = arch\n\n fn_ = 'libvirt_domain.jinja'\n try:\n template = JINJA.get_template(fn_)\n except jinja2.exceptions.TemplateNotFound:\n log.error('Could not load template %s', fn_)\n return ''\n\n return template.render(**context)\n", "def _gen_vol_xml(vmname,\n diskname,\n disktype,\n size,\n pool):\n '''\n Generate the XML string to define a libvirt storage volume\n '''\n size = int(size) * 1024 # MB\n context = {\n 'name': vmname,\n 'filename': '{0}.{1}'.format(diskname, disktype),\n 'volname': diskname,\n 'disktype': disktype,\n 'size': six.text_type(size),\n 'pool': pool,\n }\n fn_ = 'libvirt_volume.jinja'\n try:\n template = JINJA.get_template(fn_)\n except jinja2.exceptions.TemplateNotFound:\n log.error('Could not load template %s', fn_)\n return ''\n return template.render(**context)\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n", "def _zfs_image_create(vm_name,\n pool,\n disk_name,\n hostname_property_name,\n sparse_volume,\n disk_size,\n disk_image_name):\n '''\n Clones an existing image, or creates a new one.\n\n When cloning an image, disk_image_name refers to the source\n of the clone. If not specified, disk_size is used for creating\n a new zvol, and sparse_volume determines whether to create\n a thin provisioned volume.\n\n The cloned or new volume can have a ZFS property set containing\n the vm_name. Use hostname_property_name for specifying the key\n of this ZFS property.\n '''\n if not disk_image_name and not disk_size:\n raise CommandExecutionError(\n 'Unable to create new disk {0}, please specify'\n ' the disk image name or disk size argument'\n .format(disk_name)\n )\n\n if not pool:\n raise CommandExecutionError(\n 'Unable to create new disk {0}, please specify'\n ' the disk pool name'.format(disk_name))\n\n destination_fs = os.path.join(pool,\n '{0}.{1}'.format(vm_name, disk_name))\n log.debug('Image destination will be %s', destination_fs)\n\n existing_disk = __salt__['zfs.list'](name=pool)\n if 'error' in existing_disk:\n raise CommandExecutionError(\n 'Unable to create new disk {0}. {1}'\n .format(destination_fs, existing_disk['error'])\n )\n elif destination_fs in existing_disk:\n log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs)\n blockdevice_path = os.path.join('/dev/zvol', pool, vm_name)\n return blockdevice_path\n\n properties = {}\n if hostname_property_name:\n properties[hostname_property_name] = vm_name\n\n if disk_image_name:\n __salt__['zfs.clone'](\n name_a=disk_image_name,\n name_b=destination_fs,\n properties=properties)\n\n elif disk_size:\n __salt__['zfs.create'](\n name=destination_fs,\n properties=properties,\n volume_size=disk_size,\n sparse=sparse_volume)\n\n blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}'\n .format(vm_name, disk_name))\n log.debug('Image path will be %s', blockdevice_path)\n return blockdevice_path\n", "def _qemu_image_create(disk, create_overlay=False, saltenv='base'):\n '''\n Create the image file using specified disk_size or/and disk_image\n\n Return path to the created image file\n '''\n disk_size = disk.get('size', None)\n disk_image = disk.get('image', None)\n\n if not disk_size and not disk_image:\n raise CommandExecutionError(\n 'Unable to create new disk {0}, please specify'\n ' disk size and/or disk image argument'\n .format(disk['filename'])\n )\n\n img_dest = disk['source_file']\n log.debug('Image destination will be %s', img_dest)\n img_dir = os.path.dirname(img_dest)\n log.debug('Image destination directory is %s', img_dir)\n if not os.path.exists(img_dir):\n os.makedirs(img_dir)\n\n if disk_image:\n log.debug('Create disk from specified image %s', disk_image)\n sfn = __salt__['cp.cache_file'](disk_image, saltenv)\n\n qcow2 = False\n if salt.utils.path.which('qemu-img'):\n res = __salt__['cmd.run']('qemu-img info {}'.format(sfn))\n imageinfo = salt.utils.yaml.safe_load(res)\n qcow2 = imageinfo['file format'] == 'qcow2'\n try:\n if create_overlay and qcow2:\n log.info('Cloning qcow2 image %s using copy on write', sfn)\n __salt__['cmd.run'](\n 'qemu-img create -f qcow2 -o backing_file={0} {1}'\n .format(sfn, img_dest).split())\n else:\n log.debug('Copying %s to %s', sfn, img_dest)\n salt.utils.files.copyfile(sfn, img_dest)\n\n mask = salt.utils.files.get_umask()\n\n if disk_size and qcow2:\n log.debug('Resize qcow2 image to %sM', disk_size)\n __salt__['cmd.run'](\n 'qemu-img resize {0} {1}M'\n .format(img_dest, disk_size)\n )\n\n log.debug('Apply umask and remove exec bit')\n mode = (0o0777 ^ mask) & 0o0666\n os.chmod(img_dest, mode)\n\n except (IOError, OSError) as err:\n raise CommandExecutionError(\n 'Problem while copying image. {0} - {1}'\n .format(disk_image, err)\n )\n\n else:\n # Create empty disk\n try:\n mask = salt.utils.files.get_umask()\n\n if disk_size:\n log.debug('Create empty image with size %sM', disk_size)\n __salt__['cmd.run'](\n 'qemu-img create -f {0} {1} {2}M'\n .format(disk.get('format', 'qcow2'), img_dest, disk_size)\n )\n else:\n raise CommandExecutionError(\n 'Unable to create new disk {0},'\n ' please specify <size> argument'\n .format(img_dest)\n )\n\n log.debug('Apply umask and remove exec bit')\n mode = (0o0777 ^ mask) & 0o0666\n os.chmod(img_dest, mode)\n\n except (IOError, OSError) as err:\n raise CommandExecutionError(\n 'Problem while creating volume {0} - {1}'\n .format(img_dest, err)\n )\n\n return img_dest\n", "def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None):\n '''\n Get network devices from the profile and merge uer defined ones with them.\n '''\n nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else []\n log.debug('NIC profile is %s', nicp)\n if interfaces:\n users_nics = _complete_nics(interfaces, hypervisor)\n for unic in users_nics:\n found = [nic for nic in nicp if nic['name'] == unic['name']]\n if found:\n found[0].update(unic)\n else:\n nicp.append(unic)\n log.debug('Merged NICs: %s', nicp)\n return nicp\n", "def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name\n '''\n Define a volume based on the XML passed to the function\n\n :param xml: libvirt XML definition of the storage volume\n :param connection: libvirt connection URI, overriding defaults\n\n .. versionadded:: 2019.2.0\n :param username: username to connect with, overriding defaults\n\n .. versionadded:: 2019.2.0\n :param password: password to connect with, overriding defaults\n\n .. versionadded:: 2019.2.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' virt.define_vol_xml_str <XML in string format>\n\n The storage pool where the disk image will be defined is ``default``\n unless changed with a configuration like this:\n\n .. code-block:: yaml\n\n virt:\n storagepool: mine\n '''\n poolname = __salt__['config.get']('libvirt:storagepool', None)\n if poolname is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt:storagepool\\' has been deprecated in favor of '\n '\\'virt:storagepool\\'. \\'libvirt:storagepool\\' will stop '\n 'being used in {version}.'\n )\n else:\n poolname = __salt__['config.get']('virt:storagepool', 'default')\n\n conn = __get_conn(**kwargs)\n pool = conn.storagePoolLookupByName(six.text_type(poolname))\n ret = pool.createXML(xml, 0) is not None\n conn.close()\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_disks_equal
python
def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev')
Test if two disk elements should be considered like the same device
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1726-L1739
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_nics_equal
python
def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2)
Test if two interface elements should be considered like the same device
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1742-L1757
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_graphics_equal
python
def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2))
Test if two graphics devices should be considered the same device
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1760-L1782
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_diff_lists
python
def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff
Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1785-L1819
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_diff_disk_lists
python
def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal)
Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1822-L1843
[ "def _diff_lists(old, new, comparator):\n '''\n Compare lists to extract the changes\n\n :param old: old list\n :param new: new list\n :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys\n\n The sorted list is the union of unchanged and new lists, but keeping the original\n order from the new list.\n '''\n def _remove_indent(node):\n '''\n Remove the XML indentation to compare XML trees more easily\n '''\n node_copy = copy.deepcopy(node)\n node_copy.text = None\n for item in node_copy.iter():\n item.tail = None\n return node_copy\n\n diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []}\n # We don't want to alter old since it may be used later by caller\n old_devices = copy.deepcopy(old)\n for new_item in new:\n found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))]\n if found:\n old_devices.remove(found[0])\n diff['unchanged'].append(found[0])\n diff['sorted'].append(found[0])\n else:\n diff['new'].append(new_item)\n diff['sorted'].append(new_item)\n diff['deleted'] = old_devices\n return diff\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_diff_interface_lists
python
def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff
Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1846-L1862
[ "def _diff_lists(old, new, comparator):\n '''\n Compare lists to extract the changes\n\n :param old: old list\n :param new: new list\n :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys\n\n The sorted list is the union of unchanged and new lists, but keeping the original\n order from the new list.\n '''\n def _remove_indent(node):\n '''\n Remove the XML indentation to compare XML trees more easily\n '''\n node_copy = copy.deepcopy(node)\n node_copy.text = None\n for item in node_copy.iter():\n item.tail = None\n return node_copy\n\n diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []}\n # We don't want to alter old since it may be used later by caller\n old_devices = copy.deepcopy(old)\n for new_item in new:\n found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))]\n if found:\n old_devices.remove(found[0])\n diff['unchanged'].append(found[0])\n diff['sorted'].append(found[0])\n else:\n diff['new'].append(new_item)\n diff['sorted'].append(new_item)\n diff['deleted'] = old_devices\n return diff\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
update
python
def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status
Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L1875-L2061
[ "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n", "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs):\n '''\n Gather the disk profile from the config or apply the default based\n on the active hypervisor\n\n This is the ``default`` profile for KVM/QEMU, which can be\n overridden in the configuration:\n\n .. code-block:: yaml\n\n virt:\n disk:\n default:\n - system:\n size: 8192\n format: qcow2\n model: virtio\n\n Example profile for KVM/QEMU with two disks, first is created\n from specified image, the second is empty:\n\n .. code-block:: yaml\n\n virt:\n disk:\n two_disks:\n - system:\n size: 8192\n format: qcow2\n model: virtio\n image: http://path/to/image.qcow2\n - lvm:\n size: 32768\n format: qcow2\n model: virtio\n\n The ``format`` and ``model`` parameters are optional, and will\n default to whatever is best suitable for the active hypervisor.\n '''\n default = [{'system':\n {'size': 8192}}]\n if hypervisor == 'vmware':\n overlay = {'format': 'vmdk',\n 'model': 'scsi',\n 'device': 'disk',\n 'pool': '[{0}] '.format(pool if pool else '0')}\n elif hypervisor in ['qemu', 'kvm']:\n overlay = {'format': 'qcow2',\n 'device': 'disk',\n 'model': 'virtio'}\n elif hypervisor in ['bhyve']:\n overlay = {'format': 'raw',\n 'device': 'disk',\n 'model': 'virtio',\n 'sparse_volume': False}\n elif hypervisor == 'xen':\n overlay = {'format': 'qcow2',\n 'device': 'disk',\n 'model': 'xen'}\n else:\n overlay = {}\n\n # Get the disks from the profile\n disklist = []\n if profile:\n disklist = copy.deepcopy(\n __salt__['config.get']('virt:disk', {}).get(profile, default))\n\n # Transform the list to remove one level of dictionnary and add the name as a property\n disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()]\n\n # Add the image to the first disk if there is one\n if image:\n # If image is specified in module arguments, then it will be used\n # for the first disk instead of the image from the disk profile\n log.debug('%s image from module arguments will be used for disk \"%s\"'\n ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', \"\"))\n disklist[0]['image'] = image\n\n # Merge with the user-provided disks definitions\n if disks:\n for udisk in disks:\n if 'name' in udisk:\n found = [disk for disk in disklist if udisk['name'] == disk['name']]\n if found:\n found[0].update(udisk)\n else:\n disklist.append(udisk)\n\n for disk in disklist:\n # Add the missing properties that have defaults\n for key, val in six.iteritems(overlay):\n if key not in disk:\n disk[key] = val\n\n # We may have an already computed source_file (i.e. image not created by our module)\n if 'source_file' in disk and disk['source_file']:\n disk['filename'] = os.path.basename(disk['source_file'])\n elif 'source_file' not in disk:\n _fill_disk_filename(vm_name, disk, hypervisor, **kwargs)\n\n return disklist\n", "def _gen_xml(name,\n cpu,\n mem,\n diskp,\n nicp,\n hypervisor,\n os_type,\n arch,\n graphics=None,\n loader=None,\n **kwargs):\n '''\n Generate the XML string to define a libvirt VM\n '''\n mem = int(mem) * 1024 # MB\n context = {\n 'hypervisor': hypervisor,\n 'name': name,\n 'cpu': six.text_type(cpu),\n 'mem': six.text_type(mem),\n }\n if hypervisor in ['qemu', 'kvm']:\n context['controller_model'] = False\n elif hypervisor == 'vmware':\n # TODO: make bus and model parameterized, this works for 64-bit Linux\n context['controller_model'] = 'lsilogic'\n\n # By default, set the graphics to listen to all addresses\n if graphics:\n if 'listen' not in graphics:\n graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'}\n elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address':\n graphics['listen']['address'] = '0.0.0.0'\n\n # Graphics of type 'none' means no graphics device at all\n if graphics.get('type', 'none') == 'none':\n graphics = None\n context['graphics'] = graphics\n\n if loader and 'path' not in loader:\n log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration')\n loader = None\n elif loader:\n loader_attributes = []\n for key, val in loader.items():\n if key == 'path':\n continue\n loader_attributes.append(\"{key}='{val}'\".format(key=key, val=val))\n loader['_attributes'] = ' '.join(loader_attributes)\n\n if 'boot_dev' in kwargs:\n context['boot_dev'] = []\n for dev in kwargs['boot_dev'].split():\n context['boot_dev'].append(dev)\n else:\n context['boot_dev'] = ['hd']\n\n context['loader'] = loader\n\n if os_type == 'xen':\n # Compute the Xen PV boot method\n if __grains__['os_family'] == 'Suse':\n context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen'\n context['boot_dev'] = []\n\n if 'serial_type' in kwargs:\n context['serial_type'] = kwargs['serial_type']\n if 'serial_type' in context and context['serial_type'] == 'tcp':\n if 'telnet_port' in kwargs:\n context['telnet_port'] = kwargs['telnet_port']\n else:\n context['telnet_port'] = 23023 # FIXME: use random unused port\n if 'serial_type' in context:\n if 'console' in kwargs:\n context['console'] = kwargs['console']\n else:\n context['console'] = True\n\n context['disks'] = []\n disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'}\n for i, disk in enumerate(diskp):\n prefix = disk_bus_map.get(disk['model'], 'sd')\n disk_context = {\n 'device': disk.get('device', 'disk'),\n 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]),\n 'disk_bus': disk['model'],\n 'type': disk['format'],\n 'index': six.text_type(i),\n }\n if 'source_file' and disk['source_file']:\n disk_context['source_file'] = disk['source_file']\n\n if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']:\n disk_context['address'] = False\n disk_context['driver'] = True\n elif hypervisor in ['esxi', 'vmware']:\n disk_context['address'] = True\n disk_context['driver'] = False\n context['disks'].append(disk_context)\n context['nics'] = nicp\n\n context['os_type'] = os_type\n context['arch'] = arch\n\n fn_ = 'libvirt_domain.jinja'\n try:\n template = JINJA.get_template(fn_)\n except jinja2.exceptions.TemplateNotFound:\n log.error('Could not load template %s', fn_)\n return ''\n\n return template.render(**context)\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n", "def _qemu_image_create(disk, create_overlay=False, saltenv='base'):\n '''\n Create the image file using specified disk_size or/and disk_image\n\n Return path to the created image file\n '''\n disk_size = disk.get('size', None)\n disk_image = disk.get('image', None)\n\n if not disk_size and not disk_image:\n raise CommandExecutionError(\n 'Unable to create new disk {0}, please specify'\n ' disk size and/or disk image argument'\n .format(disk['filename'])\n )\n\n img_dest = disk['source_file']\n log.debug('Image destination will be %s', img_dest)\n img_dir = os.path.dirname(img_dest)\n log.debug('Image destination directory is %s', img_dir)\n if not os.path.exists(img_dir):\n os.makedirs(img_dir)\n\n if disk_image:\n log.debug('Create disk from specified image %s', disk_image)\n sfn = __salt__['cp.cache_file'](disk_image, saltenv)\n\n qcow2 = False\n if salt.utils.path.which('qemu-img'):\n res = __salt__['cmd.run']('qemu-img info {}'.format(sfn))\n imageinfo = salt.utils.yaml.safe_load(res)\n qcow2 = imageinfo['file format'] == 'qcow2'\n try:\n if create_overlay and qcow2:\n log.info('Cloning qcow2 image %s using copy on write', sfn)\n __salt__['cmd.run'](\n 'qemu-img create -f qcow2 -o backing_file={0} {1}'\n .format(sfn, img_dest).split())\n else:\n log.debug('Copying %s to %s', sfn, img_dest)\n salt.utils.files.copyfile(sfn, img_dest)\n\n mask = salt.utils.files.get_umask()\n\n if disk_size and qcow2:\n log.debug('Resize qcow2 image to %sM', disk_size)\n __salt__['cmd.run'](\n 'qemu-img resize {0} {1}M'\n .format(img_dest, disk_size)\n )\n\n log.debug('Apply umask and remove exec bit')\n mode = (0o0777 ^ mask) & 0o0666\n os.chmod(img_dest, mode)\n\n except (IOError, OSError) as err:\n raise CommandExecutionError(\n 'Problem while copying image. {0} - {1}'\n .format(disk_image, err)\n )\n\n else:\n # Create empty disk\n try:\n mask = salt.utils.files.get_umask()\n\n if disk_size:\n log.debug('Create empty image with size %sM', disk_size)\n __salt__['cmd.run'](\n 'qemu-img create -f {0} {1} {2}M'\n .format(disk.get('format', 'qcow2'), img_dest, disk_size)\n )\n else:\n raise CommandExecutionError(\n 'Unable to create new disk {0},'\n ' please specify <size> argument'\n .format(img_dest)\n )\n\n log.debug('Apply umask and remove exec bit')\n mode = (0o0777 ^ mask) & 0o0666\n os.chmod(img_dest, mode)\n\n except (IOError, OSError) as err:\n raise CommandExecutionError(\n 'Problem while creating volume {0} - {1}'\n .format(img_dest, err)\n )\n\n return img_dest\n", "def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None):\n '''\n Get network devices from the profile and merge uer defined ones with them.\n '''\n nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else []\n log.debug('NIC profile is %s', nicp)\n if interfaces:\n users_nics = _complete_nics(interfaces, hypervisor)\n for unic in users_nics:\n found = [nic for nic in nicp if nic['name'] == unic['name']]\n if found:\n found[0].update(unic)\n else:\n nicp.append(unic)\n log.debug('Merged NICs: %s', nicp)\n return nicp\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
list_domains
python
def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms
Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2064-L2089
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
list_active_vms
python
def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms
Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2092-L2117
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
list_inactive_vms
python
def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms
Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2120-L2145
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
vm_info
python
def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info
Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2148-L2212
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n", "def _info(dom):\n '''\n Compute the infos of a domain\n '''\n raw = dom.info()\n return {'cpu': raw[3],\n 'cputime': int(raw[4]),\n 'disks': _get_disks(dom),\n 'graphics': _get_graphics(dom),\n 'nics': _get_nics(dom),\n 'uuid': _get_uuid(dom),\n 'loader': _get_loader(dom),\n 'on_crash': _get_on_crash(dom),\n 'on_reboot': _get_on_reboot(dom),\n 'on_poweroff': _get_on_poweroff(dom),\n 'maxMem': int(raw[1]),\n 'mem': int(raw[2]),\n 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')}\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
vm_state
python
def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info
Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2215-L2255
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n", "def _info(dom):\n '''\n Compute domain state\n '''\n state = ''\n raw = dom.info()\n state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')\n return state\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
_node_info
python
def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info
Internal variant of node_info taking a libvirt connection as parameter
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2258-L2271
null
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
node_info
python
def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info
Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2274-L2297
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _node_info(conn):\n '''\n Internal variant of node_info taking a libvirt connection as parameter\n '''\n raw = conn.getInfo()\n info = {'cpucores': raw[6],\n 'cpumhz': raw[3],\n 'cpumodel': six.text_type(raw[0]),\n 'cpus': raw[2],\n 'cputhreads': raw[7],\n 'numanodes': raw[4],\n 'phymemory': raw[1],\n 'sockets': raw[5]}\n return info\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
get_nics
python
def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics
Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2300-L2324
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_nics(dom):\n '''\n Get domain network interfaces from a libvirt domain object.\n '''\n nics = {}\n doc = ElementTree.fromstring(dom.XMLDesc(0))\n for iface_node in doc.findall('devices/interface'):\n nic = {}\n nic['type'] = iface_node.get('type')\n for v_node in iface_node:\n if v_node.tag == 'mac':\n nic['mac'] = v_node.get('address')\n if v_node.tag == 'model':\n nic['model'] = v_node.get('type')\n if v_node.tag == 'target':\n nic['target'] = v_node.get('dev')\n # driver, source, and match can all have optional attributes\n if re.match('(driver|source|address)', v_node.tag):\n temp = {}\n for key, value in six.iteritems(v_node.attrib):\n temp[key] = value\n nic[v_node.tag] = temp\n # virtualport needs to be handled separately, to pick up the\n # type attribute of the virtualport itself\n if v_node.tag == 'virtualport':\n temp = {}\n temp['type'] = v_node.get('type')\n for key, value in six.iteritems(v_node.attrib):\n temp[key] = value\n nic['virtualport'] = temp\n if 'mac' not in nic:\n continue\n nics[nic['mac']] = nic\n return nics\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
get_macs
python
def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')]
Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2327-L2349
[ "def get_xml(vm_, **kwargs):\n '''\n Returns the XML for a given vm\n\n :param vm_: domain name\n :param connection: libvirt connection URI, overriding defaults\n\n .. versionadded:: 2019.2.0\n :param username: username to connect with, overriding defaults\n\n .. versionadded:: 2019.2.0\n :param password: password to connect with, overriding defaults\n\n .. versionadded:: 2019.2.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' virt.get_xml <domain>\n '''\n conn = __get_conn(**kwargs)\n xml_desc = _get_domain(conn, vm_).XMLDesc(0)\n conn.close()\n return xml_desc\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
get_graphics
python
def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics
Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2352-L2376
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n", "def _get_graphics(dom):\n '''\n Get domain graphics from a libvirt domain object.\n '''\n out = {'autoport': 'None',\n 'keymap': 'None',\n 'listen': 'None',\n 'port': 'None',\n 'type': 'None'}\n doc = ElementTree.fromstring(dom.XMLDesc(0))\n for g_node in doc.findall('devices/graphics'):\n for key, value in six.iteritems(g_node.attrib):\n out[key] = value\n return out\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
get_loader
python
def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader
Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2379-L2399
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_loader(dom):\n '''\n Get domain loader from a libvirt domain object.\n '''\n out = {'path': 'None'}\n doc = ElementTree.fromstring(dom.XMLDesc(0))\n for g_node in doc.findall('os/loader'):\n out['path'] = g_node.text\n for key, value in six.iteritems(g_node.attrib):\n out[key] = value\n return out\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
get_disks
python
def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks
Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2402-L2426
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n", "def _get_disks(dom):\n '''\n Get domain disks from a libvirt domain object.\n '''\n disks = {}\n doc = ElementTree.fromstring(dom.XMLDesc(0))\n for elem in doc.findall('devices/disk'):\n source = elem.find('source')\n if source is None:\n continue\n target = elem.find('target')\n if target is None:\n continue\n if 'dev' in target.attrib:\n qemu_target = source.get('file', '')\n if not qemu_target:\n qemu_target = source.get('dev', '')\n elif qemu_target.startswith('/dev/zvol/'):\n disks[target.get('dev')] = {\n 'file': qemu_target,\n 'zfs': True}\n continue\n if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network\n qemu_target = '{0}:{1}'.format(\n source.get('protocol'),\n source.get('name'))\n if not qemu_target:\n continue\n\n disk = {'file': qemu_target, 'type': elem.get('device')}\n\n driver = elem.find('driver')\n if driver is not None and driver.get('type') == 'qcow2':\n try:\n stdout = subprocess.Popen(\n ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']],\n shell=False,\n stdout=subprocess.PIPE).communicate()[0]\n qemu_output = salt.utils.stringutils.to_str(stdout)\n output = _parse_qemu_img_info(qemu_output)\n disk.update(output)\n except TypeError:\n disk.update({'file': 'Does not exist'})\n\n disks[target.get('dev')] = disk\n return disks\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0 def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()
saltstack/salt
salt/modules/virt.py
setmem
python
def setmem(vm_, memory, config=False, **kwargs): ''' Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # libvirt has a funny bitwise system for the flags in that the flag # to affect the "current" setting is 0, which means that to set the # current setting we have to call it a second time with just 0 set flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setMemoryFlags(memory * 1024, flags) ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() # return True if both calls succeeded return ret1 == ret2 == 0
Changes the amount of memory allocated to VM. The VM must be shutdown for this to work. :param vm_: name of the domain :param memory: memory amount to set in MB :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setmem <domain> <size> salt '*' virt.setmem my_domain 768
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2429-L2473
[ "def __get_conn(**kwargs):\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n\n :param connection: libvirt connection URI, overriding defaults\n :param username: username to connect with, overriding defaults\n :param password: password to connect with, overriding defaults\n\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n # Connection string works on bhyve, but auth is not tested.\n\n username = kwargs.get('username', None)\n password = kwargs.get('password', None)\n conn_str = kwargs.get('connection', None)\n if not conn_str:\n conn_str = __salt__['config.get']('virt.connect', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'virt.connect\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'virt.connect\\' will stop being used in '\n '{version}.'\n )\n else:\n conn_str = __salt__['config.get']('libvirt:connection', None)\n if conn_str is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.connection\\' configuration property has been deprecated in favor '\n 'of \\'virt:connection:uri\\'. \\'libvirt.connection\\' will stop being used in '\n '{version}.'\n )\n\n conn_str = __salt__['config.get']('virt:connection:uri', conn_str)\n\n hypervisor = __salt__['config.get']('libvirt:hypervisor', None)\n if hypervisor is not None:\n salt.utils.versions.warn_until(\n 'Sodium',\n '\\'libvirt.hypervisor\\' configuration property has been deprecated. '\n 'Rather use the \\'virt:connection:uri\\' to properly define the libvirt '\n 'URI or alias of the host to connect to. \\'libvirt:hypervisor\\' will '\n 'stop being used in {version}.'\n )\n\n if hypervisor == 'esxi' and conn_str is None:\n salt.utils.versions.warn_until(\n 'Sodium',\n 'esxi hypervisor default with no default connection URI detected, '\n 'please set \\'virt:connection:uri\\' to \\'esx\\' for keep the legacy '\n 'behavior. Will default to libvirt guess once \\'libvirt:hypervisor\\' '\n 'configuration is removed in {version}.'\n )\n conn_str = 'esx'\n\n try:\n auth_types = [libvirt.VIR_CRED_AUTHNAME,\n libvirt.VIR_CRED_NOECHOPROMPT,\n libvirt.VIR_CRED_ECHOPROMPT,\n libvirt.VIR_CRED_PASSPHRASE,\n libvirt.VIR_CRED_EXTERNAL]\n conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0)\n except Exception:\n raise CommandExecutionError(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software at {1}'.format(\n __grains__['fqdn'],\n conn_str\n )\n )\n return conn\n", "def _get_domain(conn, *vms, **kwargs):\n '''\n Return a domain object for the named VM or return domain object for all VMs.\n\n :params conn: libvirt connection object\n :param vms: list of domain names to look for\n :param iterable: True to return an array in all cases\n '''\n ret = list()\n lookup_vms = list()\n\n all_vms = []\n if kwargs.get('active', True):\n for id_ in conn.listDomainsID():\n all_vms.append(conn.lookupByID(id_).name())\n\n if kwargs.get('inactive', True):\n for id_ in conn.listDefinedDomains():\n all_vms.append(id_)\n\n if not all_vms:\n raise CommandExecutionError('No virtual machines found.')\n\n if vms:\n for name in vms:\n if name not in all_vms:\n raise CommandExecutionError('The VM \"{name}\" is not present'.format(name=name))\n else:\n lookup_vms.append(name)\n else:\n lookup_vms = list(all_vms)\n\n for name in lookup_vms:\n ret.append(conn.lookupByName(name))\n\n return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret\n" ]
# -*- coding: utf-8 -*- ''' Work with virtual machines managed by libvirt :depends: libvirt Python module Connection ========== The connection to the virtualization host can be either setup in the minion configuration, pillar data or overridden for each individual call. By default, the libvirt connection URL will be guessed: the first available libvirt hypervisor driver will be used. This can be overridden like this: .. code-block:: yaml virt: connection: uri: lxc:/// If the connection requires an authentication like for ESXi, this can be defined in the minion pillar data like this: .. code-block:: yaml virt: connection: uri: esx://10.1.1.101/?no_verify=1&auto_answer=1 auth: username: user password: secret Connecting with SSH protocol ---------------------------- Libvirt can connect to remote hosts using SSH using one of the ``ssh``, ``libssh`` and ``libssh2`` transports. Note that ``libssh2`` is likely to fail as it doesn't read the ``known_hosts`` file. Libvirt may also have been built without ``libssh`` or ``libssh2`` support. To use the SSH transport, on the minion setup an SSH agent with a key authorized on the remote libvirt machine. Per call connection setup ------------------------- .. versionadded:: 2019.2.0 All the calls requiring the libvirt connection configuration as mentioned above can override this configuration using ``connection``, ``username`` and ``password`` parameters. This means that the following will list the domains on the local LXC libvirt driver, whatever the ``virt:connection`` is. .. code-block:: bash salt 'hypervisor' virt.list_domains connection=lxc:/// The calls not using the libvirt connection setup are: - ``seed_non_shared_migrate`` - ``virt_type`` - ``is_*hyper`` - all migration functions - `libvirt ESX URI format <http://libvirt.org/drvesx.html#uriformat>`_ - `libvirt URI format <http://libvirt.org/uri.html#URI_config>`_ - `libvirt authentication configuration <http://libvirt.org/auth.html#Auth_client_config>`_ ''' # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import os import re import sys import shutil import subprocess import string # pylint: disable=deprecated-module import logging import time import datetime from xml.etree import ElementTree # Import third party libs import jinja2 import jinja2.exceptions try: import libvirt # pylint: disable=import-error from libvirt import libvirtError HAS_LIBVIRT = True except ImportError: HAS_LIBVIRT = False # Import salt libs import salt.utils.files import salt.utils.json import salt.utils.network import salt.utils.path import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net import salt.utils.versions import salt.utils.yaml from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.ext import six from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt') ) ) VIRT_STATE_NAME_MAP = {0: 'running', 1: 'running', 2: 'running', 3: 'paused', 4: 'shutdown', 5: 'shutdown', 6: 'crashed'} def __virtual__(): if not HAS_LIBVIRT: return (False, 'Unable to locate or import python libvirt library.') return 'virt' def __get_request_auth(username, password): ''' Get libvirt.openAuth callback with username, password values overriding the configuration ones. ''' # pylint: disable=unused-argument def __request_auth(credentials, user_data): '''Callback method passed to libvirt.openAuth(). The credentials argument is a list of credentials that libvirt would like to request. An element of this list is a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME - a prompt to be displayed to the user - a challenge - a default result for the request - a place to store the actual result for the request The user_data argument is currently not set in the openAuth call. ''' for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: credential[4] = username if username else \ __salt__['config.get']('virt:connection:auth:username', credential[3]) elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: credential[4] = password if password else \ __salt__['config.get']('virt:connection:auth:password', credential[3]) else: log.info('Unhandled credential type: %s', credential[0]) return 0 def __get_conn(**kwargs): ''' Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ''' # This has only been tested on kvm and xen, it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve, but auth is not tested. username = kwargs.get('username', None) password = kwargs.get('password', None) conn_str = kwargs.get('connection', None) if not conn_str: conn_str = __salt__['config.get']('virt.connect', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.connect\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'virt.connect\' will stop being used in ' '{version}.' ) else: conn_str = __salt__['config.get']('libvirt:connection', None) if conn_str is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.connection\' configuration property has been deprecated in favor ' 'of \'virt:connection:uri\'. \'libvirt.connection\' will stop being used in ' '{version}.' ) conn_str = __salt__['config.get']('virt:connection:uri', conn_str) hypervisor = __salt__['config.get']('libvirt:hypervisor', None) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt.hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) if hypervisor == 'esxi' and conn_str is None: salt.utils.versions.warn_until( 'Sodium', 'esxi hypervisor default with no default connection URI detected, ' 'please set \'virt:connection:uri\' to \'esx\' for keep the legacy ' 'behavior. Will default to libvirt guess once \'libvirt:hypervisor\' ' 'configuration is removed in {version}.' ) conn_str = 'esx' try: auth_types = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_EXTERNAL] conn = libvirt.openAuth(conn_str, [auth_types, __get_request_auth(username, password), None], 0) except Exception: raise CommandExecutionError( 'Sorry, {0} failed to open a connection to the hypervisor ' 'software at {1}'.format( __grains__['fqdn'], conn_str ) ) return conn def _get_domain(conn, *vms, **kwargs): ''' Return a domain object for the named VM or return domain object for all VMs. :params conn: libvirt connection object :param vms: list of domain names to look for :param iterable: True to return an array in all cases ''' ret = list() lookup_vms = list() all_vms = [] if kwargs.get('active', True): for id_ in conn.listDomainsID(): all_vms.append(conn.lookupByID(id_).name()) if kwargs.get('inactive', True): for id_ in conn.listDefinedDomains(): all_vms.append(id_) if not all_vms: raise CommandExecutionError('No virtual machines found.') if vms: for name in vms: if name not in all_vms: raise CommandExecutionError('The VM "{name}" is not present'.format(name=name)) else: lookup_vms.append(name) else: lookup_vms = list(all_vms) for name in lookup_vms: ret.append(conn.lookupByName(name)) return len(ret) == 1 and not kwargs.get('iterable') and ret[0] or ret def _parse_qemu_img_info(info): ''' Parse qemu-img info JSON output into disk infos dictionary ''' raw_infos = salt.utils.json.loads(info) disks = [] for disk_infos in raw_infos: disk = { 'file': disk_infos['filename'], 'file format': disk_infos['format'], 'disk size': disk_infos['actual-size'], 'virtual size': disk_infos['virtual-size'], 'cluster size': disk_infos['cluster-size'] if 'cluster-size' in disk_infos else None, } if 'full-backing-filename' in disk_infos.keys(): disk['backing file'] = format(disk_infos['full-backing-filename']) if 'snapshots' in disk_infos.keys(): disk['snapshots'] = [ { 'id': snapshot['id'], 'tag': snapshot['name'], 'vmsize': snapshot['vm-state-size'], 'date': datetime.datetime.fromtimestamp( float('{}.{}'.format(snapshot['date-sec'], snapshot['date-nsec']))).isoformat(), 'vmclock': datetime.datetime.utcfromtimestamp( float('{}.{}'.format(snapshot['vm-clock-sec'], snapshot['vm-clock-nsec']))).time().isoformat() } for snapshot in disk_infos['snapshots']] disks.append(disk) for disk in disks: if 'backing file' in disk.keys(): candidates = [info for info in disks if 'file' in info.keys() and info['file'] == disk['backing file']] if candidates: disk['backing file'] = candidates[0] return disks[0] def _get_uuid(dom): ''' Return a uuid from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_uuid <domain> ''' return ElementTree.fromstring(get_xml(dom)).find('uuid').text def _get_on_poweroff(dom): ''' Return `on_poweroff` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_restart <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_poweroff') return node.text if node is not None else '' def _get_on_reboot(dom): ''' Return `on_reboot` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_reboot <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_reboot') return node.text if node is not None else '' def _get_on_crash(dom): ''' Return `on_crash` setting from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_on_crash <domain> ''' node = ElementTree.fromstring(get_xml(dom)).find('on_crash') return node.text if node is not None else '' def _get_nics(dom): ''' Get domain network interfaces from a libvirt domain object. ''' nics = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for iface_node in doc.findall('devices/interface'): nic = {} nic['type'] = iface_node.get('type') for v_node in iface_node: if v_node.tag == 'mac': nic['mac'] = v_node.get('address') if v_node.tag == 'model': nic['model'] = v_node.get('type') if v_node.tag == 'target': nic['target'] = v_node.get('dev') # driver, source, and match can all have optional attributes if re.match('(driver|source|address)', v_node.tag): temp = {} for key, value in six.iteritems(v_node.attrib): temp[key] = value nic[v_node.tag] = temp # virtualport needs to be handled separately, to pick up the # type attribute of the virtualport itself if v_node.tag == 'virtualport': temp = {} temp['type'] = v_node.get('type') for key, value in six.iteritems(v_node.attrib): temp[key] = value nic['virtualport'] = temp if 'mac' not in nic: continue nics[nic['mac']] = nic return nics def _get_graphics(dom): ''' Get domain graphics from a libvirt domain object. ''' out = {'autoport': 'None', 'keymap': 'None', 'listen': 'None', 'port': 'None', 'type': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('devices/graphics'): for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_loader(dom): ''' Get domain loader from a libvirt domain object. ''' out = {'path': 'None'} doc = ElementTree.fromstring(dom.XMLDesc(0)) for g_node in doc.findall('os/loader'): out['path'] = g_node.text for key, value in six.iteritems(g_node.attrib): out[key] = value return out def _get_disks(dom): ''' Get domain disks from a libvirt domain object. ''' disks = {} doc = ElementTree.fromstring(dom.XMLDesc(0)) for elem in doc.findall('devices/disk'): source = elem.find('source') if source is None: continue target = elem.find('target') if target is None: continue if 'dev' in target.attrib: qemu_target = source.get('file', '') if not qemu_target: qemu_target = source.get('dev', '') elif qemu_target.startswith('/dev/zvol/'): disks[target.get('dev')] = { 'file': qemu_target, 'zfs': True} continue if not qemu_target and 'protocol' in source.attrib and 'name' in source.attrib: # for rbd network qemu_target = '{0}:{1}'.format( source.get('protocol'), source.get('name')) if not qemu_target: continue disk = {'file': qemu_target, 'type': elem.get('device')} driver = elem.find('driver') if driver is not None and driver.get('type') == 'qcow2': try: stdout = subprocess.Popen( ['qemu-img', 'info', '--output', 'json', '--backing-chain', disk['file']], shell=False, stdout=subprocess.PIPE).communicate()[0] qemu_output = salt.utils.stringutils.to_str(stdout) output = _parse_qemu_img_info(qemu_output) disk.update(output) except TypeError: disk.update({'file': 'Does not exist'}) disks[target.get('dev')] = disk return disks def _libvirt_creds(): ''' Returns the user and group that the disk images should be owned by ''' g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf' u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf' try: stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] group = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: group = 'root' try: stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] user = salt.utils.stringutils.to_str(stdout).split('"')[1] except IndexError: user = 'root' return {'user': user, 'group': group} def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'virt:tunnel\'. \'virt.tunnel\' will stop ' 'being used in {version}.') else: tunnel = __salt__['config.get']('virt:tunnel') if tunnel: return ('virsh migrate --p2p --tunnelled --live --persistent ' '--undefinesource ') return 'virsh migrate --live --persistent --undefinesource ' def _get_target(target, ssh): ''' Compute libvirt URL for target migration host. ''' proto = 'qemu' if ssh: proto += '+ssh' return ' {0}://{1}/{2}'.format(proto, target, 'system') def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): ''' Generate the XML string to define a libvirt VM ''' mem = int(mem) * 1024 # MB context = { 'hypervisor': hypervisor, 'name': name, 'cpu': six.text_type(cpu), 'mem': six.text_type(mem), } if hypervisor in ['qemu', 'kvm']: context['controller_model'] = False elif hypervisor == 'vmware': # TODO: make bus and model parameterized, this works for 64-bit Linux context['controller_model'] = 'lsilogic' # By default, set the graphics to listen to all addresses if graphics: if 'listen' not in graphics: graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'} elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address': graphics['listen']['address'] = '0.0.0.0' # Graphics of type 'none' means no graphics device at all if graphics.get('type', 'none') == 'none': graphics = None context['graphics'] = graphics if loader and 'path' not in loader: log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration') loader = None elif loader: loader_attributes = [] for key, val in loader.items(): if key == 'path': continue loader_attributes.append("{key}='{val}'".format(key=key, val=val)) loader['_attributes'] = ' '.join(loader_attributes) if 'boot_dev' in kwargs: context['boot_dev'] = [] for dev in kwargs['boot_dev'].split(): context['boot_dev'].append(dev) else: context['boot_dev'] = ['hd'] context['loader'] = loader if os_type == 'xen': # Compute the Xen PV boot method if __grains__['os_family'] == 'Suse': context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen' context['boot_dev'] = [] if 'serial_type' in kwargs: context['serial_type'] = kwargs['serial_type'] if 'serial_type' in context and context['serial_type'] == 'tcp': if 'telnet_port' in kwargs: context['telnet_port'] = kwargs['telnet_port'] else: context['telnet_port'] = 23023 # FIXME: use random unused port if 'serial_type' in context: if 'console' in kwargs: context['console'] = kwargs['console'] else: context['console'] = True context['disks'] = [] disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'} for i, disk in enumerate(diskp): prefix = disk_bus_map.get(disk['model'], 'sd') disk_context = { 'device': disk.get('device', 'disk'), 'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]), 'disk_bus': disk['model'], 'type': disk['format'], 'index': six.text_type(i), } if 'source_file' and disk['source_file']: disk_context['source_file'] = disk['source_file'] if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']: disk_context['address'] = False disk_context['driver'] = True elif hypervisor in ['esxi', 'vmware']: disk_context['address'] = True disk_context['driver'] = False context['disks'].append(disk_context) context['nics'] = nicp context['os_type'] = os_type context['arch'] = arch fn_ = 'libvirt_domain.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(diskname, disktype), 'volname': diskname, 'disktype': disktype, 'size': six.text_type(size), 'pool': pool, } fn_ = 'libvirt_volume.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_net_xml(name, bridge, forward, vport, tag=None): ''' Generate the XML string to define a libvirt network ''' context = { 'name': name, 'bridge': bridge, 'forward': forward, 'vport': vport, 'tag': tag, } fn_ = 'libvirt_network.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _gen_pool_xml(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None): ''' Generate the XML string to define a libvirt storage pool ''' hosts = [host.split(':') for host in source_hosts or []] context = { 'name': name, 'ptype': ptype, 'target': {'path': target, 'permissions': permissions}, 'source': { 'devices': source_devices or [], 'dir': source_dir, 'adapter': source_adapter, 'hosts': [{'name': host[0], 'port': host[1] if len(host) > 1 else None} for host in hosts], 'auth': source_auth, 'name': source_name, 'format': source_format } } fn_ = 'libvirt_pool.jinja' try: template = JINJA.get_template(fn_) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', fn_) return '' return template.render(**context) def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images\' has been deprecated in favor of ' '\'virt:images\'. \'virt.images\' will stop ' 'being used in {version}.') else: img_dir = __salt__['config.get']('virt:images') log.debug('Image directory from config option `virt:images`' ' is %s', img_dir) return img_dir def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cloning an image, disk_image_name refers to the source of the clone. If not specified, disk_size is used for creating a new zvol, and sparse_volume determines whether to create a thin provisioned volume. The cloned or new volume can have a ZFS property set containing the vm_name. Use hostname_property_name for specifying the key of this ZFS property. ''' if not disk_image_name and not disk_size: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk image name or disk size argument' .format(disk_name) ) if not pool: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' the disk pool name'.format(disk_name)) destination_fs = os.path.join(pool, '{0}.{1}'.format(vm_name, disk_name)) log.debug('Image destination will be %s', destination_fs) existing_disk = __salt__['zfs.list'](name=pool) if 'error' in existing_disk: raise CommandExecutionError( 'Unable to create new disk {0}. {1}' .format(destination_fs, existing_disk['error']) ) elif destination_fs in existing_disk: log.info('ZFS filesystem %s already exists. Skipping creation', destination_fs) blockdevice_path = os.path.join('/dev/zvol', pool, vm_name) return blockdevice_path properties = {} if hostname_property_name: properties[hostname_property_name] = vm_name if disk_image_name: __salt__['zfs.clone']( name_a=disk_image_name, name_b=destination_fs, properties=properties) elif disk_size: __salt__['zfs.create']( name=destination_fs, properties=properties, volume_size=disk_size, sparse=sparse_volume) blockdevice_path = os.path.join('/dev/zvol', pool, '{0}.{1}' .format(vm_name, disk_name)) log.debug('Image path will be %s', blockdevice_path) return blockdevice_path def _qemu_image_create(disk, create_overlay=False, saltenv='base'): ''' Create the image file using specified disk_size or/and disk_image Return path to the created image file ''' disk_size = disk.get('size', None) disk_image = disk.get('image', None) if not disk_size and not disk_image: raise CommandExecutionError( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' .format(disk['filename']) ) img_dest = disk['source_file'] log.debug('Image destination will be %s', img_dest) img_dir = os.path.dirname(img_dest) log.debug('Image destination directory is %s', img_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if disk_image: log.debug('Create disk from specified image %s', disk_image) sfn = __salt__['cp.cache_file'](disk_image, saltenv) qcow2 = False if salt.utils.path.which('qemu-img'): res = __salt__['cmd.run']('qemu-img info {}'.format(sfn)) imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo['file format'] == 'qcow2' try: if create_overlay and qcow2: log.info('Cloning qcow2 image %s using copy on write', sfn) __salt__['cmd.run']( 'qemu-img create -f qcow2 -o backing_file={0} {1}' .format(sfn, img_dest).split()) else: log.debug('Copying %s to %s', sfn, img_dest) salt.utils.files.copyfile(sfn, img_dest) mask = salt.utils.files.get_umask() if disk_size and qcow2: log.debug('Resize qcow2 image to %sM', disk_size) __salt__['cmd.run']( 'qemu-img resize {0} {1}M' .format(img_dest, disk_size) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while copying image. {0} - {1}' .format(disk_image, err) ) else: # Create empty disk try: mask = salt.utils.files.get_umask() if disk_size: log.debug('Create empty image with size %sM', disk_size) __salt__['cmd.run']( 'qemu-img create -f {0} {1} {2}M' .format(disk.get('format', 'qcow2'), img_dest, disk_size) ) else: raise CommandExecutionError( 'Unable to create new disk {0},' ' please specify <size> argument' .format(img_dest) ) log.debug('Apply umask and remove exec bit') mode = (0o0777 ^ mask) & 0o0666 os.chmod(img_dest, mode) except (IOError, OSError) as err: raise CommandExecutionError( 'Problem while creating volume {0} - {1}' .format(img_dest, err) ) return img_dest def _disk_profile(profile, hypervisor, disks=None, vm_name=None, image=None, pool=None, **kwargs): ''' Gather the disk profile from the config or apply the default based on the active hypervisor This is the ``default`` profile for KVM/QEMU, which can be overridden in the configuration: .. code-block:: yaml virt: disk: default: - system: size: 8192 format: qcow2 model: virtio Example profile for KVM/QEMU with two disks, first is created from specified image, the second is empty: .. code-block:: yaml virt: disk: two_disks: - system: size: 8192 format: qcow2 model: virtio image: http://path/to/image.qcow2 - lvm: size: 32768 format: qcow2 model: virtio The ``format`` and ``model`` parameters are optional, and will default to whatever is best suitable for the active hypervisor. ''' default = [{'system': {'size': 8192}}] if hypervisor == 'vmware': overlay = {'format': 'vmdk', 'model': 'scsi', 'device': 'disk', 'pool': '[{0}] '.format(pool if pool else '0')} elif hypervisor in ['qemu', 'kvm']: overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'virtio'} elif hypervisor in ['bhyve']: overlay = {'format': 'raw', 'device': 'disk', 'model': 'virtio', 'sparse_volume': False} elif hypervisor == 'xen': overlay = {'format': 'qcow2', 'device': 'disk', 'model': 'xen'} else: overlay = {} # Get the disks from the profile disklist = [] if profile: disklist = copy.deepcopy( __salt__['config.get']('virt:disk', {}).get(profile, default)) # Transform the list to remove one level of dictionnary and add the name as a property disklist = [dict(d, name=name) for disk in disklist for name, d in disk.items()] # Add the image to the first disk if there is one if image: # If image is specified in module arguments, then it will be used # for the first disk instead of the image from the disk profile log.debug('%s image from module arguments will be used for disk "%s"' ' instead of %s', image, disklist[0]['name'], disklist[0].get('image', "")) disklist[0]['image'] = image # Merge with the user-provided disks definitions if disks: for udisk in disks: if 'name' in udisk: found = [disk for disk in disklist if udisk['name'] == disk['name']] if found: found[0].update(udisk) else: disklist.append(udisk) for disk in disklist: # Add the missing properties that have defaults for key, val in six.iteritems(overlay): if key not in disk: disk[key] = val # We may have an already computed source_file (i.e. image not created by our module) if 'source_file' in disk and disk['source_file']: disk['filename'] = os.path.basename(disk['source_file']) elif 'source_file' not in disk: _fill_disk_filename(vm_name, disk, hypervisor, **kwargs) return disklist def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs): ''' Compute the disk file name and update it in the disk value. ''' base_dir = disk.get('pool', None) if hypervisor in ['qemu', 'kvm', 'xen']: # Compute the base directory from the pool property. We may have either a path # or a libvirt pool name there. # If the pool is a known libvirt one with a target path, use it as target path if not base_dir: base_dir = _get_images_dir() else: if not base_dir.startswith('/'): # The pool seems not to be a path, lookup for pool infos infos = pool_info(base_dir, **kwargs) pool = infos[base_dir] if base_dir in infos else None if not pool or not pool['target_path'] or pool['target_path'].startswith('/dev'): raise CommandExecutionError( 'Unable to create new disk {0}, specified pool {1} does not exist ' 'or is unsupported'.format(disk['name'], base_dir)) base_dir = pool['target_path'] if hypervisor == 'bhyve' and vm_name: disk['filename'] = '{0}.{1}'.format(vm_name, disk['name']) disk['source_file'] = os.path.join('/dev/zvol', base_dir or '', disk['filename']) elif vm_name: # Compute the filename and source file properties if possible disk['filename'] = '{0}_{1}.{2}'.format(vm_name, disk['name'], disk['format']) disk['source_file'] = os.path.join(base_dir, disk['filename']) def _complete_nics(interfaces, hypervisor, dmac=None): ''' Complete missing data for network interfaces. ''' vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'} kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'} bhyve_overlay = {'type': 'bridge', 'source': 'bridge0', 'model': 'virtio'} xen_overlay = {'type': 'bridge', 'source': 'br0', 'model': None} overlays = { 'xen': xen_overlay, 'kvm': kvm_overlay, 'qemu': kvm_overlay, 'vmware': vmware_overlay, 'bhyve': bhyve_overlay, } def _normalize_net_types(attributes): ''' Guess which style of definition: bridge: br0 or network: net0 or type: network source: net0 ''' for type_ in ['bridge', 'network']: if type_ in attributes: attributes['type'] = type_ # we want to discard the original key attributes['source'] = attributes.pop(type_) attributes['type'] = attributes.get('type', None) attributes['source'] = attributes.get('source', None) def _apply_default_overlay(attributes): ''' Apply the default overlay to attributes ''' for key, value in six.iteritems(overlays[hypervisor]): if key not in attributes or not attributes[key]: attributes[key] = value def _assign_mac(attributes, hypervisor): ''' Compute mac address for NIC depending on hypervisor ''' if dmac is not None: log.debug('Default MAC address is %s', dmac) if salt.utils.validate.net.mac(dmac): attributes['mac'] = dmac else: msg = 'Malformed MAC address: {0}'.format(dmac) raise CommandExecutionError(msg) else: if hypervisor in ['qemu', 'kvm']: attributes['mac'] = salt.utils.network.gen_mac( prefix='52:54:00') else: attributes['mac'] = salt.utils.network.gen_mac() for interface in interfaces: _normalize_net_types(interface) if interface.get('mac', None) is None: _assign_mac(interface, hypervisor) if hypervisor in overlays: _apply_default_overlay(interface) return interfaces def _nic_profile(profile_name, hypervisor, dmac=None): ''' Compute NIC data based on profile ''' default = [{'eth0': {}}] # support old location config_data = __salt__['config.option']('virt.nic', {}).get( profile_name, None ) if config_data is not None: salt.utils.versions.warn_until( 'Sodium', '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. ' '\'virt.nic\' will stop being used in {version}.' ) else: config_data = __salt__['config.get']('virt:nic', {}).get( profile_name, default ) interfaces = [] # pylint: disable=invalid-name def append_dict_profile_to_interface_list(profile_dict): ''' Append dictionary profile data to interfaces list ''' for interface_name, attributes in six.iteritems(profile_dict): attributes['name'] = interface_name interfaces.append(attributes) # old style dicts (top-level dicts) # # virt: # nic: # eth0: # bridge: br0 # eth1: # network: test_net if isinstance(config_data, dict): append_dict_profile_to_interface_list(config_data) # new style lists (may contain dicts) # # virt: # nic: # - eth0: # bridge: br0 # - eth1: # network: test_net # # virt: # nic: # - name: eth0 # bridge: br0 # - name: eth1 # network: test_net elif isinstance(config_data, list): for interface in config_data: if isinstance(interface, dict): if len(interface) == 1: append_dict_profile_to_interface_list(interface) else: interfaces.append(interface) # dmac can only be used from init() return _complete_nics(interfaces, hypervisor, dmac=dmac) def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics = _complete_nics(interfaces, hypervisor) for unic in users_nics: found = [nic for nic in nicp if nic['name'] == unic['name']] if found: found[0].update(unic) else: nicp.append(unic) log.debug('Merged NICs: %s', nicp) return nicp def init(name, cpu, mem, image=None, nic='default', interfaces=None, hypervisor=None, start=True, # pylint: disable=redefined-outer-name disk='default', disks=None, saltenv='base', seed=True, install=True, pub_key=None, priv_key=None, seed_cmd='seed.apply', enable_vnc=False, enable_qcow=False, graphics=None, os_type=None, arch=None, loader=None, **kwargs): ''' Initialize a new vm :param name: name of the virtual machine to create :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param image: Path to a disk image to use as the first disk (Default: ``None``). Deprecated in favor of the ``disks`` parameter. To set (or change) the image of a disk, add the following to the disks definitions: .. code-block:: python { 'name': 'name_of_disk_to_change', 'image': '/path/to/the/image' } :param nic: NIC profile to use (Default: ``'default'``). The profile interfaces can be customized / extended with the interfaces parameter. If set to ``None``, no profile will be used. :param interfaces: List of dictionaries providing details on the network interfaces to create. These data are merged with the ones from the nic profile. The structure of each dictionary is documented in init-nic-def_. .. versionadded:: 2019.2.0 :param hypervisor: the virtual machine type. By default the value will be computed according to the virtual host capabilities. :param start: ``True`` to start the virtual machine after having defined it (Default: ``True``) :param disk: Disk profile to use (Default: ``'default'``). If set to ``None``, no profile will be used. :param disks: List of dictionaries providing details on the disk devices to create. These data are merged with the ones from the disk profile. The structure of each dictionary is documented in init-disk-def_. .. versionadded:: 2019.2.0 :param saltenv: Fileserver environment (Default: ``'base'``) :param seed: ``True`` to seed the disk image. Only used when the ``image`` parameter is provided. (Default: ``True``) :param install: install salt minion if absent (Default: ``True``) :param pub_key: public key to seed with (Default: ``None``) :param priv_key: public key to seed with (Default: ``None``) :param seed_cmd: Salt command to execute to seed the image. (Default: ``'seed.apply'``) :param enable_vnc: ``True`` to setup a vnc display for the VM (Default: ``False``) Deprecated in favor of the ``graphics`` parameter. Could be replaced with the following: .. code-block:: python graphics={'type': 'vnc'} .. deprecated:: 2019.2.0 :param graphics: Dictionary providing details on the graphics device to create. (Default: ``None``) See init-graphics-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param loader: Dictionary providing details on the BIOS firmware loader. (Default: ``None``) See init-loader-def_ for more details on the possible values. .. versionadded:: 2019.2.0 :param os_type: type of virtualization as found in the ``//os/type`` element of the libvirt definition. The default value is taken from the host capabilities, with a preference for ``hvm``. .. versionadded:: 2019.2.0 :param arch: architecture of the virtual machine. The default value is taken from the host capabilities, but ``x86_64`` is prefed over ``i686``. .. versionadded:: 2019.2.0 :param enable_qcow: ``True`` to create a QCOW2 overlay image, rather than copying the image (Default: ``False``). Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to create an overlay image of a template disk image with an image set: .. code-block:: python { 'name': 'name_of_disk_to_change', 'overlay_image': True } .. deprecated:: 2019.2.0 :param pool: Path of the folder where the image files are located for vmware/esx hypervisors. Deprecated in favor of ``disks`` parameter. Add the following to the disks definitions to set the vmware datastore of a disk image: .. code-block:: python { 'name': 'name_of_disk_to_change', 'pool': 'mydatastore' } .. deprecated:: Flurorine :param dmac: Default MAC address to use for the network interfaces. By default MAC addresses are automatically generated. Deprecated in favor of ``interfaces`` parameter. Add the following to the interfaces definitions to force the mac address of a NIC: .. code-block:: python { 'name': 'name_of_nic_to_change', 'mac': 'MY:MA:CC:ADD:RE:SS' } .. deprecated:: 2019.2.0 :param config: minion configuration to use when seeding. See :mod:`seed module <salt.modules.seed>` for more details :param boot_dev: String of space-separated devices to boot from (Default: ``'hd'``) :param serial_type: Serial device type. One of ``'pty'``, ``'tcp'`` (Default: ``None``) :param telnet_port: Telnet port to use for serial device of type ``tcp``. :param console: ``True`` to add a console device along with serial one (Default: ``True``) :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. _init-nic-def: **Network Interface Definitions** Network interfaces dictionaries can contain the following properties: name Name of the network interface. This is only used as a key to merge with the profile data type Network type. One of ``'bridge'``, ``'network'`` source The network source, typically the bridge or network name mac The desired mac address, computed if ``None`` (Default: ``None``). model The network card model (Default: depends on the hypervisor) .. _init-disk-def: **Disk Definitions** Disk dictionaries can contain the following properties: name Name of the disk. This is mostly used in the name of the disk image and as a key to merge with the profile data. format Format of the disk image, like ``'qcow2'``, ``'raw'``, ``'vmdk'``. (Default: depends on the hypervisor) size Disk size in MiB pool Path to the folder or name of the pool where disks should be created. (Default: depends on hypervisor) model One of the disk busses allowed by libvirt (Default: depends on hypervisor) See the libvirt `disk element`_ documentation for the allowed bus types. image Path to the image to use for the disk. If no image is provided, an empty disk will be created (Default: ``None``) overlay_image ``True`` to create a QCOW2 disk image with ``image`` as backing file. If ``False`` the file pointed to by the ``image`` property will simply be copied. (Default: ``False``) hostname_property When using ZFS volumes, setting this value to a ZFS property ID will make Salt store the name of the virtual machine inside this property. (Default: ``None``) sparse_volume Boolean to specify whether to use a thin provisioned ZFS volume. Example profile for a bhyve VM with two ZFS disks. The first is cloned from the specified image. The second disk is a thin provisioned volume. .. code-block:: yaml virt: disk: two_zvols: - system: image: zroot/bhyve/CentOS-7-x86_64-v1@v1.0.5 hostname_property: virt:hostname pool: zroot/bhyve/guests - data: pool: tank/disks size: 20G hostname_property: virt:hostname sparse_volume: True source_file Absolute path to the disk image to use. Not to be confused with ``image`` parameter. This parameter is useful to use disk images that are created outside of this module. Can also be ``None`` for devices that have no associated image like cdroms. device Type of device of the disk. Can be one of 'disk', 'cdrom', 'floppy' or 'lun'. (Default: ``'disk'``) .. _init-graphics-def: **Graphics Definition** The graphics dictionnary can have the following properties: type Graphics type. The possible values are ``none``, ``'spice'``, ``'vnc'`` and other values allowed as a libvirt graphics type (Default: ``None``) See the libvirt `graphics element`_ documentation for more details on the possible types. port Port to export the graphics on for ``vnc``, ``spice`` and ``rdp`` types. tls_port Port to export the graphics over a secured connection for ``spice`` type. listen Dictionary defining on what address to listen on for ``vnc``, ``spice`` and ``rdp``. It has a ``type`` property with ``address`` and ``None`` as possible values, and an ``address`` property holding the IP or hostname to listen on. By default, not setting the ``listen`` part of the dictionary will default to listen on all addresses. .. _init-loader-def: **Loader Definition** The loader dictionary must have the following property: path Path to the UEFI firmware binary Optionally, you can provide arbitrary attributes such as ``readonly`` or ``type``. See the libvirt documentation for all supported loader parameters. CLI Example: .. code-block:: bash salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw salt 'hypervisor' virt.init vm_name 4 512 /var/lib/libvirt/images/img.raw salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile The disk images will be created in an image folder within the directory defined by the ``virt:images`` option. Its default value is ``/srv/salt-images/`` but this can changed with such a configuration: .. code-block:: yaml virt: images: /data/my/vm/images/ .. _disk element: https://libvirt.org/formatdomain.html#elementsDisks .. _graphics element: https://libvirt.org/formatdomain.html#elementsGraphics ''' caps = capabilities(**kwargs) os_types = sorted({guest['os_type'] for guest in caps['guests']}) arches = sorted({guest['arch']['name'] for guest in caps['guests']}) if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor) if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] # esxi used to be a possible value for the hypervisor: map it to vmware since it's the same hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor log.debug('Using hypervisor %s', hypervisor) # the NICs are computed as follows: # 1 - get the default NICs from the profile # 2 - Complete the users NICS # 3 - Update the default NICS list to the users one, matching key is the name dmac = kwargs.get('dmac', None) if dmac: salt.utils.versions.warn_until( 'Sodium', '\'dmac\' parameter has been deprecated. Rather use the \'interfaces\' parameter ' 'to properly define the desired MAC address. \'dmac\' will be removed in {version}.' ) nicp = _get_merged_nics(hypervisor, nic, interfaces, dmac=dmac) # the disks are computed as follows: # 1 - get the disks defined in the profile # 2 - set the image on the first disk (will be removed later) # 3 - update the disks from the profile with the ones from the user. The matching key is the name. pool = kwargs.get('pool', None) if pool: salt.utils.versions.warn_until( 'Sodium', '\'pool\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to properly define the vmware datastore of disks. \'pool\' will be removed in {version}.' ) if image: salt.utils.versions.warn_until( 'Sodium', '\'image\' parameter has been deprecated. Rather use the \'disks\' parameter ' 'to override or define the image. \'image\' will be removed in {version}.' ) diskp = _disk_profile(disk, hypervisor, disks, name, image=image, pool=pool, **kwargs) # Create multiple disks, empty or from specified images. for _disk in diskp: log.debug("Creating disk for VM [ %s ]: %s", name, _disk) if hypervisor == 'vmware': if 'image' in _disk: # TODO: we should be copying the image file onto the ESX host raise SaltInvocationError( 'virt.init does not support image ' 'template in conjunction with esxi hypervisor' ) else: # assume libvirt manages disks for us log.debug('Generating libvirt XML for %s', _disk) vol_xml = _gen_vol_xml( name, _disk['name'], _disk['format'], _disk['size'], _disk['pool'] ) define_vol_xml_str(vol_xml) elif hypervisor in ['qemu', 'kvm', 'xen']: create_overlay = enable_qcow if create_overlay: salt.utils.versions.warn_until( 'Sodium', '\'enable_qcow\' parameter has been deprecated. Rather use the \'disks\' ' 'parameter to override or define the image. \'enable_qcow\' will be removed ' 'in {version}.' ) else: create_overlay = _disk.get('overlay_image', False) if _disk['source_file']: if os.path.exists(_disk['source_file']): img_dest = _disk['source_file'] else: img_dest = _qemu_image_create(_disk, create_overlay, saltenv) else: img_dest = None # Seed only if there is an image specified if seed and img_dest and _disk.get('image', None): log.debug('Seed command is %s', seed_cmd) __salt__[seed_cmd]( img_dest, id_=name, config=kwargs.get('config'), install=install, pub_key=pub_key, priv_key=priv_key, ) elif hypervisor in ['bhyve']: img_dest = _zfs_image_create( vm_name=name, pool=_disk.get('pool'), disk_name=_disk.get('name'), disk_size=_disk.get('size'), disk_image_name=_disk.get('image'), hostname_property_name=_disk.get('hostname_property'), sparse_volume=_disk.get('sparse_volume'), ) else: # Unknown hypervisor raise SaltInvocationError( 'Unsupported hypervisor when handling disk image: {0}' .format(hypervisor) ) log.debug('Generating VM XML') if enable_vnc: salt.utils.versions.warn_until( 'Sodium', '\'enable_vnc\' parameter has been deprecated in favor of ' '\'graphics\'. Use graphics={\'type\': \'vnc\'} for the same behavior. ' '\'enable_vnc\' will be removed in {version}. ') graphics = {'type': 'vnc'} if os_type is None: os_type = 'hvm' if 'hvm' in os_types else os_types[0] if arch is None: arch = 'x86_64' if 'x86_64' in arches else arches[0] vm_xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics, loader, **kwargs) conn = __get_conn(**kwargs) try: conn.defineXML(vm_xml) except libvirtError as err: # check if failure is due to this domain already existing if "domain '{}' already exists".format(name) in six.text_type(err): # continue on to seeding log.warning(err) else: conn.close() raise err # a real error we should report upwards if start: log.debug('Starting VM %s', name) _get_domain(conn, name).create() conn.close() return True def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None return source1 == source2 and \ target1 is not None and target2 is not None and \ target1.get('bus') == target2.get('bus') and \ disk1.get('device', 'disk') == disk2.get('device', 'disk') and \ target1.get('dev') == target2.get('dev') def _nics_equal(nic1, nic2): ''' Test if two interface elements should be considered like the same device ''' def _filter_nic(nic): ''' Filter out elements to ignore when comparing nics ''' return { 'type': nic.attrib['type'], 'source': nic.find('source').attrib[nic.attrib['type']] if nic.find('source') is not None else None, 'mac': nic.find('mac').attrib['address'].lower() if nic.find('mac') is not None else None, 'model': nic.find('model').attrib['type'] if nic.find('model') is not None else None, } return _filter_nic(nic1) == _filter_nic(nic2) def _graphics_equal(gfx1, gfx2): ''' Test if two graphics devices should be considered the same device ''' def _filter_graphics(gfx): ''' When the domain is running, the graphics element may contain additional properties with the default values. This function will strip down the default values. ''' gfx_copy = copy.deepcopy(gfx) defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']}, {'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']}, {'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}] for default in defaults: node = gfx_copy.find(default['node']) attrib = default['attrib'] if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']): node.set(attrib, default['values'][0]) return gfx_copy return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2)) def _diff_lists(old, new, comparator): ''' Compare lists to extract the changes :param old: old list :param new: new list :return: a dictionary with ``unchanged``, ``new``, ``deleted`` and ``sorted`` keys The sorted list is the union of unchanged and new lists, but keeping the original order from the new list. ''' def _remove_indent(node): ''' Remove the XML indentation to compare XML trees more easily ''' node_copy = copy.deepcopy(node) node_copy.text = None for item in node_copy.iter(): item.tail = None return node_copy diff = {'unchanged': [], 'new': [], 'deleted': [], 'sorted': []} # We don't want to alter old since it may be used later by caller old_devices = copy.deepcopy(old) for new_item in new: found = [item for item in old_devices if comparator(_remove_indent(item), _remove_indent(new_item))] if found: old_devices.remove(found[0]) diff['unchanged'].append(found[0]) diff['sorted'].append(found[0]) else: diff['new'].append(new_item) diff['sorted'].append(new_item) diff['deleted'] = old_devices return diff def _diff_disk_lists(old, new): ''' Compare disk definitions to extract the changes and fix target devices :param old: list of ElementTree nodes representing the old disks :param new: list of ElementTree nodes representing the new disks ''' # Change the target device to avoid duplicates before diffing: this may lead # to additional changes. Think of unchanged disk 'hda' and another disk listed # before it becoming 'hda' too... the unchanged need to turn into 'hdb'. targets = [] prefixes = ['fd', 'hd', 'vd', 'sd', 'xvd', 'ubd'] for disk in new: target_node = disk.find('target') target = target_node.get('dev') prefix = [item for item in prefixes if target.startswith(item)][0] new_target = ['{0}{1}'.format(prefix, string.ascii_lowercase[i]) for i in range(len(new)) if '{0}{1}'.format(prefix, string.ascii_lowercase[i]) not in targets][0] target_node.set('dev', new_target) targets.append(new_target) return _diff_lists(old, new, _disks_equal) def _diff_interface_lists(old, new): ''' Compare network interface definitions to extract the changes :param old: list of ElementTree nodes representing the old interfaces :param new: list of ElementTree nodes representing the new interfaces ''' diff = _diff_lists(old, new, _nics_equal) # Remove duplicated addresses mac addresses and let libvirt generate them for us macs = [nic.find('mac').get('address') for nic in diff['unchanged']] for nic in diff['new']: mac = nic.find('mac') if mac.get('address') in macs: nic.remove(mac) return diff def _diff_graphics_lists(old, new): ''' Compare graphic devices definitions to extract the changes :param old: list of ElementTree nodes representing the old graphic devices :param new: list of ElementTree nodes representing the new graphic devices ''' return _diff_lists(old, new, _graphics_equal) def update(name, cpu=0, mem=0, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, live=True, **kwargs): ''' Update the definition of an existing domain. :param name: Name of the domain to update :param cpu: Number of virtual CPUs to assign to the virtual machine :param mem: Amount of memory to allocate to the virtual machine in MiB. :param disk_profile: disk profile to use :param disks: Disk definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the disk devices will not be changed. However to clear disks set this parameter to empty list. :param nic_profile: network interfaces profile to use :param interfaces: Network interface definitions as documented in the :func:`init` function. If neither the profile nor this parameter are defined, the interface devices will not be changed. However to clear network interfaces set this parameter to empty list. :param graphics: The new graphics definition as defined in init-graphics-def_. If not set, the graphics will not be changed. To remove a graphics device, set this parameter to ``{'type': 'none'}``. :param live: ``False`` to avoid trying to live update the definition. In such a case, the new definition is applied at the next start of the virtual machine. If ``True``, not all aspects of the definition can be live updated, but as much as possible will be attempted. (Default: ``True``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults :return: Returns a dictionary indicating the status of what has been done. It is structured in the following way: .. code-block:: python { 'definition': True, 'cpu': True, 'mem': True, 'disks': {'attached': [list of actually attached disks], 'detached': [list of actually detached disks]}, 'nics': {'attached': [list of actually attached nics], 'detached': [list of actually detached nics]}, 'errors': ['error messages for failures'] } .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.update domain cpu=2 mem=1024 ''' status = { 'definition': False, 'disk': {'attached': [], 'detached': []}, 'interface': {'attached': [], 'detached': []} } conn = __get_conn(**kwargs) domain = _get_domain(conn, name) desc = ElementTree.fromstring(domain.XMLDesc(0)) need_update = False # Compute the XML to get the disks, interfaces and graphics hypervisor = desc.get('type') all_disks = _disk_profile(disk_profile, hypervisor, disks, name, **kwargs) new_desc = ElementTree.fromstring(_gen_xml(name, cpu, mem, all_disks, _get_merged_nics(hypervisor, nic_profile, interfaces), hypervisor, domain.OSType(), desc.find('.//os/type').get('arch'), graphics, **kwargs)) # Update the cpu cpu_node = desc.find('vcpu') if cpu and int(cpu_node.text) != cpu: cpu_node.text = six.text_type(cpu) cpu_node.set('current', six.text_type(cpu)) need_update = True # Update the memory, note that libvirt outputs all memory sizes in KiB for mem_node_name in ['memory', 'currentMemory']: mem_node = desc.find(mem_node_name) if mem and int(mem_node.text) != mem * 1024: mem_node.text = six.text_type(mem) mem_node.set('unit', 'MiB') need_update = True # Update the XML definition with the new disks and diff changes devices_node = desc.find('devices') parameters = {'disk': ['disks', 'disk_profile'], 'interface': ['interfaces', 'nic_profile'], 'graphics': ['graphics']} changes = {} for dev_type in parameters: changes[dev_type] = {} func_locals = locals() if [param for param in parameters[dev_type] if func_locals.get(param, None) is not None]: old = devices_node.findall(dev_type) new = new_desc.findall('devices/{0}'.format(dev_type)) changes[dev_type] = globals()['_diff_{0}_lists'.format(dev_type)](old, new) if changes[dev_type]['deleted'] or changes[dev_type]['new']: for item in old: devices_node.remove(item) devices_node.extend(changes[dev_type]['sorted']) need_update = True # Set the new definition if need_update: # Create missing disks if needed if changes['disk']: for idx, item in enumerate(changes['disk']['sorted']): source_file = all_disks[idx]['source_file'] if item in changes['disk']['new'] and source_file and not os.path.isfile(source_file): _qemu_image_create(all_disks[idx]) try: conn.defineXML(salt.utils.stringutils.to_str(ElementTree.tostring(desc))) status['definition'] = True except libvirt.libvirtError as err: conn.close() raise err # Do the live changes now that we know the definition has been properly set # From that point on, failures are not blocking to try to live update as much # as possible. commands = [] if domain.isActive() and live: if cpu: commands.append({'device': 'cpu', 'cmd': 'setVcpusFlags', 'args': [cpu, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) if mem: commands.append({'device': 'mem', 'cmd': 'setMemoryFlags', 'args': [mem * 1024, libvirt.VIR_DOMAIN_AFFECT_LIVE]}) for dev_type in ['disk', 'interface']: for added in changes[dev_type].get('new', []): commands.append({'device': dev_type, 'cmd': 'attachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(added))]}) for removed in changes[dev_type].get('deleted', []): commands.append({'device': dev_type, 'cmd': 'detachDevice', 'args': [salt.utils.stringutils.to_str(ElementTree.tostring(removed))]}) for cmd in commands: try: ret = getattr(domain, cmd['cmd'])(*cmd['args']) device_type = cmd['device'] if device_type in ['cpu', 'mem']: status[device_type] = not bool(ret) else: actions = {'attachDevice': 'attached', 'detachDevice': 'detached'} status[device_type][actions[cmd['cmd']]].append(cmd['args'][0]) except libvirt.libvirtError as err: if 'errors' not in status: status['errors'] = [] status['errors'].append(six.text_type(err)) conn.close() return status def list_domains(**kwargs): ''' Return a list of available domains. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True): vms.append(dom.name()) conn.close() return vms def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_active_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, inactive=False): vms.append(dom.name()) conn.close() return vms def list_inactive_vms(**kwargs): ''' Return a list of names for inactive virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_inactive_vms ''' vms = [] conn = __get_conn(**kwargs) for dom in _get_domain(conn, iterable=True, active=False): vms.append(dom.name()) conn.close() return vms def vm_info(vm_=None, **kwargs): ''' Return detailed information about the vms on this hyper in a list of dicts: :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cpu': <int>, 'maxMem': <int>, 'mem': <int>, 'state': '<state>', 'cputime' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_info ''' def _info(dom): ''' Compute the infos of a domain ''' raw = dom.info() return {'cpu': raw[3], 'cputime': int(raw[4]), 'disks': _get_disks(dom), 'graphics': _get_graphics(dom), 'nics': _get_nics(dom), 'uuid': _get_uuid(dom), 'loader': _get_loader(dom), 'on_crash': _get_on_crash(dom), 'on_reboot': _get_on_reboot(dom), 'on_poweroff': _get_on_poweroff(dom), 'maxMem': int(raw[1]), 'mem': int(raw[2]), 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')} info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_state(vm_=None, **kwargs): ''' Return list of all the vms and their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.vm_state <domain> ''' def _info(dom): ''' Compute domain state ''' state = '' raw = dom.info() state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown') return state info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def _node_info(conn): ''' Internal variant of node_info taking a libvirt connection as parameter ''' raw = conn.getInfo() info = {'cpucores': raw[6], 'cpumhz': raw[3], 'cpumodel': six.text_type(raw[0]), 'cpus': raw[2], 'cputhreads': raw[7], 'numanodes': raw[4], 'phymemory': raw[1], 'sockets': raw[5]} return info def node_info(**kwargs): ''' Return a dict with information about this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.node_info ''' conn = __get_conn(**kwargs) info = _node_info(conn) conn.close() return info def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_nics <domain> ''' conn = __get_conn(**kwargs) nics = _get_nics(_get_domain(conn, vm_)) conn.close() return nics def get_macs(vm_, **kwargs): ''' Return a list off MAC addresses from the named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_macs <domain> ''' doc = ElementTree.fromstring(get_xml(vm_, **kwargs)) return [node.get('address') for node in doc.findall('devices/interface/mac')] def get_graphics(vm_, **kwargs): ''' Returns the information on vnc for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_graphics <domain> ''' conn = __get_conn(**kwargs) graphics = _get_graphics(_get_domain(conn, vm_)) conn.close() return graphics def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.get_loader <domain> .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) loader = _get_loader(_get_domain(conn, vm_)) conn.close() return loader def get_disks(vm_, **kwargs): ''' Return the disks of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_disks <domain> ''' conn = __get_conn(**kwargs) disks = _get_disks(_get_domain(conn, vm_)) conn.close() return disks def setvcpus(vm_, vcpus, config=False, **kwargs): ''' Changes the amount of vcpus allocated to VM. The VM must be shutdown for this to work. If config is True then we ask libvirt to modify the config as well :param vm_: name of the domain :param vcpus: integer representing the number of CPUs to be assigned :param config: if True then libvirt will be asked to modify the config as well :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.setvcpus <domain> <amount> salt '*' virt.setvcpus my_domain 4 ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown': return False # see notes in setmem flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM if config: flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG ret1 = dom.setVcpusFlags(vcpus, flags) ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT) conn.close() return ret1 == ret2 == 0 def _freemem(conn): ''' Internal variant of freemem taking a libvirt connection as parameter ''' mem = conn.getInfo()[1] # Take off just enough to sustain the hypervisor mem -= 256 for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: mem -= dom.info()[2] / 1024 return mem def freemem(**kwargs): ''' Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freemem ''' conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem def _freecpu(conn): ''' Internal variant of freecpu taking a libvirt connection as parameter ''' cpus = conn.getInfo()[2] for dom in _get_domain(conn, iterable=True): if dom.ID() > 0: cpus -= dom.info()[3] return cpus def freecpu(**kwargs): ''' Return an int representing the number of unallocated cpus on this hypervisor :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.freecpu ''' conn = __get_conn(**kwargs) cpus = _freecpu(conn) conn.close() return cpus def full_info(**kwargs): ''' Return the node_info, vm_info and freemem :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.full_info ''' conn = __get_conn(**kwargs) info = {'freecpu': _freecpu(conn), 'freemem': _freemem(conn), 'node_info': _node_info(conn), 'vm_info': vm_info()} conn.close() return info def get_xml(vm_, **kwargs): ''' Returns the XML for a given vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_xml <domain> ''' conn = __get_conn(**kwargs) xml_desc = _get_domain(conn, vm_).XMLDesc(0) conn.close() return xml_desc def get_profiles(hypervisor=None, **kwargs): ''' Return the virt profiles for hypervisor. Currently there are profiles for: - nic - disk :param hypervisor: override the default machine type. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.get_profiles salt '*' virt.get_profiles hypervisor=esxi ''' ret = {} caps = capabilities(**kwargs) hypervisors = sorted({x for y in [guest['arch']['domains'].keys() for guest in caps['guests']] for x in y}) default_hypervisor = 'kvm' if 'kvm' in hypervisors else hypervisors[0] if not hypervisor: hypervisor = __salt__['config.get']('libvirt:hypervisor') if hypervisor is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:hypervisor\' configuration property has been deprecated. ' 'Rather use the \'virt:connection:uri\' to properly define the libvirt ' 'URI or alias of the host to connect to. \'libvirt:hypervisor\' will ' 'stop being used in {version}.' ) else: # Use the machine types as possible values # Prefer 'kvm' over the others if available hypervisor = default_hypervisor virtconf = __salt__['config.get']('virt', {}) for typ in ['disk', 'nic']: _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ)) ret[typ] = {'default': _func('default', hypervisor)} if typ in virtconf: ret.setdefault(typ, {}) for prf in virtconf[typ]: ret[typ][prf] = _func(prf, hypervisor) return ret def shutdown(vm_, **kwargs): ''' Send a soft shutdown signal to the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.shutdown <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.shutdown() == 0 conn.close() return ret def pause(vm_, **kwargs): ''' Pause the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pause <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.suspend() == 0 conn.close() return ret def resume(vm_, **kwargs): ''' Resume the named vm :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.resume <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.resume() == 0 conn.close() return ret def start(name, **kwargs): ''' Start a defined domain :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.start <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).create() == 0 conn.close() return ret def stop(name, **kwargs): ''' Hard power down the virtual machine, this is equivalent to pulling the power. :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.stop <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).destroy() == 0 conn.close() return ret def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reboot <domain> ''' conn = __get_conn(**kwargs) ret = _get_domain(conn, name).reboot(libvirt.VIR_DOMAIN_REBOOT_DEFAULT) == 0 conn.close() return ret def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.reset <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # reset takes a flag, like reboot, but it is not yet used # so we just pass in 0 # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset ret = dom.reset(0) == 0 conn.close() return ret def ctrl_alt_del(vm_, **kwargs): ''' Sends CTRL+ALT+DEL to a VM :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.ctrl_alt_del <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) ret = dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0 conn.close() return ret def create_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Start a transient domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.createXML(xml, 0) is not None conn.close() return ret def create_xml_path(path, **kwargs): ''' Start a transient domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.create_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return create_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a persistent domain based on the XML passed to the function :param xml: libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_str <XML in string format> ''' conn = __get_conn(**kwargs) ret = conn.defineXML(xml) is not None conn.close() return ret def define_xml_path(path, **kwargs): ''' Define a persistent domain based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def define_vol_xml_str(xml, **kwargs): # pylint: disable=redefined-outer-name ''' Define a volume based on the XML passed to the function :param xml: libvirt XML definition of the storage volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_str <XML in string format> The storage pool where the disk image will be defined is ``default`` unless changed with a configuration like this: .. code-block:: yaml virt: storagepool: mine ''' poolname = __salt__['config.get']('libvirt:storagepool', None) if poolname is not None: salt.utils.versions.warn_until( 'Sodium', '\'libvirt:storagepool\' has been deprecated in favor of ' '\'virt:storagepool\'. \'libvirt:storagepool\' will stop ' 'being used in {version}.' ) else: poolname = __salt__['config.get']('virt:storagepool', 'default') conn = __get_conn(**kwargs) pool = conn.storagePoolLookupByName(six.text_type(poolname)) ret = pool.createXML(xml, 0) is not None conn.close() return ret def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.define_vol_xml_path <path to XML file on the node> ''' try: with salt.utils.files.fopen(path, 'r') as fp_: return define_vol_xml_str( salt.utils.stringutils.to_unicode(fp_.read()), **kwargs ) except (OSError, IOError): return False def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate_non_shared_inc(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared_inc <vm name> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def migrate(vm_, target, ssh=False): ''' Shared storage migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate <domain> <target hypervisor> A tunnel data migration can be performed by setting this in the configuration: .. code-block:: yaml virt: tunnel: True For more details on tunnelled data migrations, report to https://libvirt.org/migration.html#transporttunnel ''' cmd = _get_migrate_command() + ' ' + vm_\ + _get_target(target, ssh) stdout = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] return salt.utils.stringutils.to_str(stdout) def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by virt.get_disks :param force: skip checking the compatibility of source and target disk images if True. (default: False) CLI Example: .. code-block:: bash salt '*' virt.seed_non_shared_migrate <disks> ''' for _, data in six.iteritems(disks): fn_ = data['file'] form = data['file format'] size = data['virtual size'].split()[1][1:] if os.path.isfile(fn_) and not force: # the target exists, check to see if it is compatible pre = salt.utils.yaml.safe_load(subprocess.Popen('qemu-img info arch', shell=True, stdout=subprocess.PIPE).communicate()[0]) if pre['file format'] != data['file format']\ and pre['virtual size'] != data['virtual size']: return False if not os.path.isdir(os.path.dirname(fn_)): os.makedirs(os.path.dirname(fn_)) if os.path.isfile(fn_): os.remove(fn_) cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size subprocess.call(cmd, shell=True) creds = _libvirt_creds() cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_ subprocess.call(cmd, shell=True) return True def set_autostart(vm_, state='on', **kwargs): ''' Set the autostart flag on a VM so that the VM will start with the host system on reboot. :param vm_: domain name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.set_autostart <domain> <on | off> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) # return False if state is set to something other then on or off ret = False if state == 'on': ret = dom.setAutostart(1) == 0 elif state == 'off': ret = dom.setAutostart(0) == 0 conn.close() return ret def undefine(vm_, **kwargs): ''' Remove a defined vm, this does not purge the virtual machine image, and this only works if the vm is powered down :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.undefine <domain> ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0 else: ret = dom.undefine() == 0 conn.close() return ret def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is True. This will be changed to the safer False default value in Sodium. :param vm_: domain name :param dirs: pass True to remove containing directories :param removables: pass True to remove removable devices .. versionadded:: 2019.2.0 :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.purge <domain> removables=False ''' conn = __get_conn(**kwargs) dom = _get_domain(conn, vm_) disks = _get_disks(dom) if removables is None: salt.utils.versions.warn_until( 'Sodium', 'removables argument default value is True, but will be changed ' 'to False by default in {version}. Please set to True to maintain ' 'the current behavior in the future.' ) removables = True if VIRT_STATE_NAME_MAP.get(dom.info()[0], 'unknown') != 'shutdown' and dom.destroy() != 0: return False directories = set() for disk in disks: if not removables and disks[disk]['type'] in ['cdrom', 'floppy']: continue elif disks[disk].get('zfs', False): # TODO create solution for 'dataset is busy' time.sleep(3) fs_name = disks[disk]['file'][len('/dev/zvol/'):] log.info('Destroying VM ZFS volume %s', fs_name) __salt__['zfs.destroy']( name=fs_name, force=True) else: os.remove(disks[disk]['file']) directories.add(os.path.dirname(disks[disk]['file'])) if dirs: for dir_ in directories: shutil.rmtree(dir_) if getattr(libvirt, 'VIR_DOMAIN_UNDEFINE_NVRAM', False): # This one is only in 1.2.8+ try: dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) except libvirt.libvirtError: dom.undefine() else: dom.undefine() conn.close() return True def virt_type(): ''' Returns the virtual machine type as a string CLI Example: .. code-block:: bash salt '*' virt.virt_type ''' return __grains__['virtual'] def _is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor ''' try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'kvm_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except IOError: # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_kvm_hyper(): ''' Returns a bool whether or not this node is a KVM hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_kvm_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_kvm_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "kvm" instead. ' '\'is_kvm_hyper\' will be removed in {version}.' ) return _is_kvm_hyper() def _is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor ''' try: if __grains__['virtual_subtype'] != 'Xen Dom0': return False except KeyError: # virtual_subtype isn't set everywhere. return False try: with salt.utils.files.fopen('/proc/modules') as fp_: if 'xen_' not in salt.utils.stringutils.to_unicode(fp_.read()): return False except (OSError, IOError): # No /proc/modules? Are we on Windows? Or Solaris? return False return 'libvirtd' in __salt__['cmd.run'](__grains__['ps']) def is_xen_hyper(): ''' Returns a bool whether or not this node is a XEN hypervisor CLI Example: .. code-block:: bash salt '*' virt.is_xen_hyper .. deprecated:: 2019.2.0 ''' salt.utils.versions.warn_until( 'Sodium', '\'is_xen_hyper\' function has been deprecated. Use the \'get_hypervisor\' == "xen" instead. ' '\'is_xen_hyper\' will be removed in {version}.' ) return _is_xen_hyper() def get_hypervisor(): ''' Returns the name of the hypervisor running on this node or ``None``. Detected hypervisors: - kvm - xen - bhyve CLI Example: .. code-block:: bash salt '*' virt.get_hypervisor .. versionadded:: 2019.2.0 the function and the ``kvm``, ``xen`` and ``bhyve`` hypervisors support ''' # To add a new 'foo' hypervisor, add the _is_foo_hyper function, # add 'foo' to the list below and add it to the docstring with a .. versionadded:: hypervisors = ['kvm', 'xen', 'bhyve'] result = [hyper for hyper in hypervisors if getattr(sys.modules[__name__], '_is_{}_hyper'.format(hyper))()] return result[0] if result else None def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] vmm_enabled = len(salt.utils.stringutils.to_str(stdout).split('"')[1]) != 0 except IndexError: pass return vmm_enabled def is_hyper(): ''' Returns a bool whether or not this node is a hypervisor of any kind CLI Example: .. code-block:: bash salt '*' virt.is_hyper ''' if HAS_LIBVIRT: return is_xen_hyper() or is_kvm_hyper() or _is_bhyve_hyper() return False def vm_cputime(vm_=None, **kwargs): ''' Return cputime used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'cputime' <int> 'cputime_percent' <int> }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_cputime ''' conn = __get_conn(**kwargs) host_cpus = conn.getInfo()[2] def _info(dom): ''' Compute cputime info of a domain ''' raw = dom.info() vcpus = int(raw[3]) cputime = int(raw[4]) cputime_percent = 0 if cputime: # Divide by vcpus to always return a number between 0 and 100 cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { 'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent)) } info = {} if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_netstats(vm_=None, **kwargs): ''' Return combined network counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rx_bytes' : 0, 'rx_packets' : 0, 'rx_errs' : 0, 'rx_drop' : 0, 'tx_bytes' : 0, 'tx_packets' : 0, 'tx_errs' : 0, 'tx_drop' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_netstats ''' def _info(dom): ''' Compute network stats of a domain ''' nics = _get_nics(dom) ret = { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errs': 0, 'rx_drop': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errs': 0, 'tx_drop': 0 } for attrs in six.itervalues(nics): if 'target' in attrs: dev = attrs['target'] stats = dom.interfaceStats(dev) ret['rx_bytes'] += stats[0] ret['rx_packets'] += stats[1] ret['rx_errs'] += stats[2] ret['rx_drop'] += stats[3] ret['tx_bytes'] += stats[4] ret['tx_packets'] += stats[5] ret['tx_errs'] += stats[6] ret['tx_drop'] += stats[7] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: for domain in _get_domain(conn, iterable=True): info[domain.name()] = _info(domain) conn.close() return info def vm_diskstats(vm_=None, **kwargs): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. code-block:: python [ 'your-vm': { 'rd_req' : 0, 'rd_bytes' : 0, 'wr_req' : 0, 'wr_bytes' : 0, 'errs' : 0 }, ... ] If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs. CLI Example: .. code-block:: bash salt '*' virt.vm_blockstats ''' def get_disk_devs(dom): ''' Extract the disk devices names from the domain XML definition ''' doc = ElementTree.fromstring(get_xml(dom, **kwargs)) return [target.get('dev') for target in doc.findall('devices/disk/target')] def _info(dom): ''' Compute the disk stats of a domain ''' # Do not use get_disks, since it uses qemu-img and is very slow # and unsuitable for any sort of real time statistics disks = get_disk_devs(dom) ret = {'rd_req': 0, 'rd_bytes': 0, 'wr_req': 0, 'wr_bytes': 0, 'errs': 0 } for disk in disks: stats = dom.blockStats(disk) ret['rd_req'] += stats[0] ret['rd_bytes'] += stats[1] ret['wr_req'] += stats[2] ret['wr_bytes'] += stats[3] ret['errs'] += stats[4] return ret info = {} conn = __get_conn(**kwargs) if vm_: info[vm_] = _info(_get_domain(conn, vm_)) else: # Can not run function blockStats on inactive VMs for domain in _get_domain(conn, iterable=True, inactive=False): info[domain.name()] = _info(domain) conn.close() return info def _parse_snapshot_description(vm_snapshot, unix_time=False): ''' Parse XML doc and return a dict with the status values. :param xmldoc: :return: ''' ret = dict() tree = ElementTree.fromstring(vm_snapshot.getXMLDesc()) for node in tree: if node.tag == 'name': ret['name'] = node.text elif node.tag == 'creationTime': ret['created'] = datetime.datetime.fromtimestamp(float(node.text)).isoformat(' ') \ if not unix_time else float(node.text) elif node.tag == 'state': ret['running'] = node.text == 'running' ret['current'] = vm_snapshot.isCurrent() == 1 return ret def list_snapshots(domain=None, **kwargs): ''' List available snapshots for certain vm or for all. :param domain: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.list_snapshots salt '*' virt.list_snapshots <domain> ''' ret = dict() conn = __get_conn(**kwargs) for vm_domain in _get_domain(conn, *(domain and [domain] or list()), iterable=True): ret[vm_domain.name()] = [_parse_snapshot_description(snap) for snap in vm_domain.listAllSnapshots()] or 'N/A' conn.close() return ret def snapshot(domain, name=None, suffix=None, **kwargs): ''' Create a snapshot of a VM. :param domain: domain name :param name: Name of the snapshot. If the name is omitted, then will be used original domain name with ISO 8601 time as a suffix. :param suffix: Add suffix for the new name. Useful in states, where such snapshots can be distinguished from manually created. :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.snapshot <domain> ''' if name and name.lower() == domain.lower(): raise CommandExecutionError('Virtual Machine {name} is already defined. ' 'Please choose another name for the snapshot'.format(name=name)) if not name: name = "{domain}-{tsnap}".format(domain=domain, tsnap=time.strftime('%Y%m%d-%H%M%S', time.localtime())) if suffix: name = "{name}-{suffix}".format(name=name, suffix=suffix) doc = ElementTree.Element('domainsnapshot') n_name = ElementTree.SubElement(doc, 'name') n_name.text = name conn = __get_conn(**kwargs) _get_domain(conn, domain).snapshotCreateXML( salt.utils.stringutils.to_str(ElementTree.tostring(doc)) ) conn.close() return {'name': name} def delete_snapshots(name, *names, **kwargs): ''' Delete one or more snapshots of the given VM. :param name: domain name :param names: names of the snapshots to remove :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.delete_snapshots <domain> all=True salt '*' virt.delete_snapshots <domain> <snapshot> salt '*' virt.delete_snapshots <domain> <snapshot1> <snapshot2> ... ''' deleted = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) for snap in domain.listAllSnapshots(): if snap.getName() in names or not names: deleted[snap.getName()] = _parse_snapshot_description(snap) snap.delete() conn.close() available = {name: [_parse_snapshot_description(snap) for snap in domain.listAllSnapshots()] or 'N/A'} return {'available': available, 'deleted': deleted} def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): ''' Revert snapshot to the previous from current (if available) or to the specific. :param name: domain name :param vm_snapshot: name of the snapshot to revert :param cleanup: Remove all newer than reverted snapshots. Values: True or False (default False). :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' virt.revert <domain> salt '*' virt.revert <domain> <snapshot> ''' ret = dict() conn = __get_conn(**kwargs) domain = _get_domain(conn, name) snapshots = domain.listAllSnapshots() _snapshots = list() for snap_obj in snapshots: _snapshots.append({'idx': _parse_snapshot_description(snap_obj, unix_time=True)['created'], 'ptr': snap_obj}) snapshots = [w_ptr['ptr'] for w_ptr in sorted(_snapshots, key=lambda item: item['idx'], reverse=True)] del _snapshots if not snapshots: conn.close() raise CommandExecutionError('No snapshots found') elif len(snapshots) == 1: conn.close() raise CommandExecutionError('Cannot revert to itself: only one snapshot is available.') snap = None for p_snap in snapshots: if not vm_snapshot: if p_snap.isCurrent() and snapshots[snapshots.index(p_snap) + 1:]: snap = snapshots[snapshots.index(p_snap) + 1:][0] break elif p_snap.getName() == vm_snapshot: snap = p_snap break if not snap: conn.close() raise CommandExecutionError( snapshot and 'Snapshot "{0}" not found'.format(vm_snapshot) or 'No more previous snapshots available') elif snap.isCurrent(): conn.close() raise CommandExecutionError('Cannot revert to the currently running snapshot.') domain.revertToSnapshot(snap) ret['reverted'] = snap.getName() if cleanup: delete = list() for p_snap in snapshots: if p_snap.getName() != snap.getName(): delete.append(p_snap.getName()) p_snap.delete() else: break ret['deleted'] = delete else: ret['deleted'] = 'N/A' conn.close() return ret def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name name = canonical machine = machines.get(name) if not machine: machine = {'alternate_names': []} if maxcpus: machine['maxcpus'] = int(maxcpus) machines[name] = machine if alternate_name: machine['alternate_names'].append(alternate_name) def _parse_caps_guest(guest): ''' Parse the <guest> element of the connection capabilities XML ''' arch_node = guest.find('arch') result = { 'os_type': guest.find('os_type').text, 'arch': { 'name': arch_node.get('name'), 'machines': {}, 'domains': {} }, } for child in arch_node: if child.tag == 'wordsize': result['arch']['wordsize'] = int(child.text) elif child.tag == 'emulator': result['arch']['emulator'] = child.text elif child.tag == 'machine': _caps_add_machine(result['arch']['machines'], child) elif child.tag == 'domain': domain_type = child.get('type') domain = { 'emulator': None, 'machines': {} } emulator_node = child.find('emulator') if emulator_node is not None: domain['emulator'] = emulator_node.text for machine in child.findall('machine'): _caps_add_machine(domain['machines'], machine) result['arch']['domains'][domain_type] = domain # Note that some features have no default and toggle attributes. # This may not be a perfect match, but represent them as enabled by default # without possibility to toggle them. # Some guests may also have no feature at all (xen pv for instance) features_nodes = guest.find('features') if features_nodes is not None: result['features'] = {child.tag: {'toggle': True if child.get('toggle') == 'yes' else False, 'default': True if child.get('default') == 'no' else True} for child in features_nodes} return result def _parse_caps_cell(cell): ''' Parse the <cell> nodes of the connection capabilities XML output. ''' result = { 'id': int(cell.get('id')) } mem_node = cell.find('memory') if mem_node is not None: unit = mem_node.get('unit', 'KiB') memory = mem_node.text result['memory'] = "{} {}".format(memory, unit) pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')), 'available': int(page.text)} for page in cell.findall('pages')] if pages: result['pages'] = pages distances = {int(distance.get('id')): int(distance.get('value')) for distance in cell.findall('distances/sibling')} if distances: result['distances'] = distances cpus = [] for cpu_node in cell.findall('cpus/cpu'): cpu = { 'id': int(cpu_node.get('id')) } socket_id = cpu_node.get('socket_id') if socket_id: cpu['socket_id'] = int(socket_id) core_id = cpu_node.get('core_id') if core_id: cpu['core_id'] = int(core_id) siblings = cpu_node.get('siblings') if siblings: cpu['siblings'] = siblings cpus.append(cpu) if cpus: result['cpus'] = cpus return result def _parse_caps_bank(bank): ''' Parse the <bank> element of the connection capabilities XML. ''' result = { 'id': int(bank.get('id')), 'level': int(bank.get('level')), 'type': bank.get('type'), 'size': "{} {}".format(bank.get('size'), bank.get('unit')), 'cpus': bank.get('cpus') } controls = [] for control in bank.findall('control'): unit = control.get('unit') result_control = { 'granularity': "{} {}".format(control.get('granularity'), unit), 'type': control.get('type'), 'maxAllocs': int(control.get('maxAllocs')) } minimum = control.get('min') if minimum: result_control['min'] = "{} {}".format(minimum, unit) controls.append(result_control) if controls: result['controls'] = controls return result def _parse_caps_host(host): ''' Parse the <host> element of the connection capabilities XML. ''' result = {} for child in host: if child.tag == 'uuid': result['uuid'] = child.text elif child.tag == 'cpu': cpu = { 'arch': child.find('arch').text if child.find('arch') is not None else None, 'model': child.find('model').text if child.find('model') is not None else None, 'vendor': child.find('vendor').text if child.find('vendor') is not None else None, 'features': [feature.get('name') for feature in child.findall('feature')], 'pages': [{'size': '{} {}'.format(page.get('size'), page.get('unit', 'KiB'))} for page in child.findall('pages')] } # Parse the cpu tag microcode = child.find('microcode') if microcode is not None: cpu['microcode'] = microcode.get('version') topology = child.find('topology') if topology is not None: cpu['sockets'] = int(topology.get('sockets')) cpu['cores'] = int(topology.get('cores')) cpu['threads'] = int(topology.get('threads')) result['cpu'] = cpu elif child.tag == "power_management": result['power_management'] = [node.tag for node in child] elif child.tag == "migration_features": result['migration'] = { 'live': child.find('live') is not None, 'transports': [node.text for node in child.findall('uri_transports/uri_transport')] } elif child.tag == "topology": result['topology'] = { 'cells': [_parse_caps_cell(cell) for cell in child.findall('cells/cell')] } elif child.tag == 'cache': result['cache'] = { 'banks': [_parse_caps_bank(bank) for bank in child.findall('bank')] } result['security'] = [{ 'model': secmodel.find('model').text if secmodel.find('model') is not None else None, 'doi': secmodel.find('doi').text if secmodel.find('doi') is not None else None, 'baselabels': [{'type': label.get('type'), 'label': label.text} for label in secmodel.findall('baselabel')] } for secmodel in host.findall('secmodel')] return result def capabilities(**kwargs): ''' Return the hypervisor connection capabilities. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.capabilities ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) conn.close() return { 'host': _parse_caps_host(caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in caps.findall('guest')] } def _parse_caps_enum(node): ''' Return a tuple containing the name of the enum and the possible values ''' return (node.get('name'), [value.text for value in node.findall('value')]) def _parse_caps_cpu(node): ''' Parse the <cpu> element of the domain capabilities ''' result = {} for mode in node.findall('mode'): if not mode.get('supported') == 'yes': continue name = mode.get('name') if name == 'host-passthrough': result[name] = True elif name == 'host-model': host_model = {} model_node = mode.find('model') if model_node is not None: model = { 'name': model_node.text } vendor_id = model_node.get('vendor_id') if vendor_id: model['vendor_id'] = vendor_id fallback = model_node.get('fallback') if fallback: model['fallback'] = fallback host_model['model'] = model vendor = mode.find('vendor').text if mode.find('vendor') is not None else None if vendor: host_model['vendor'] = vendor features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')} if features: host_model['features'] = features result[name] = host_model elif name == 'custom': custom_model = {} models = {model.text: model.get('usable') for model in mode.findall('model')} if models: custom_model['models'] = models result[name] = custom_model return result def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {item[0]: item[1] for item in enums if item[0]} return result def _parse_caps_loader(node): ''' Parse the <loader> element of the domain capabilities. ''' enums = [_parse_caps_enum(enum) for enum in node.findall('enum')] result = {item[0]: item[1] for item in enums if item[0]} values = [child.text for child in node.findall('value')] if values: result['values'] = values return result def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided the libvirt default domain capabilities will be returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' result = { 'emulator': caps.find('path').text if caps.find('path') is not None else None, 'domain': caps.find('domain').text if caps.find('domain') is not None else None, 'machine': caps.find('machine').text if caps.find('machine') is not None else None, 'arch': caps.find('arch').text if caps.find('arch') is not None else None } for child in caps: if child.tag == 'vcpu' and child.get('max'): result['max_vcpus'] = int(child.get('max')) elif child.tag == 'iothreads': result['iothreads'] = child.get('supported') == 'yes' elif child.tag == 'os': result['os'] = {} loader_node = child.find('loader') if loader_node is not None and loader_node.get('supported') == 'yes': loader = _parse_caps_loader(loader_node) result['os']['loader'] = loader elif child.tag == 'cpu': cpu = _parse_caps_cpu(child) if cpu: result['cpu'] = cpu elif child.tag == 'devices': devices = _parse_caps_devices_features(child) if devices: result['devices'] = devices elif child.tag == 'features': features = _parse_caps_devices_features(child) if features: result['features'] = features return result def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs): ''' Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the given CPU architecture :param machine: return the capabilities for the given emulated machine type :param domain: return the capabilities for the given virtualization type. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults The list of the possible emulator, arch, machine and domain can be found in the host capabilities output. If none of the parameters is provided, the libvirt default one is returned. CLI Example: .. code-block:: bash salt '*' virt.domain_capabilities arch='x86_64' domain='kvm' ''' conn = __get_conn(**kwargs) result = [] try: caps = ElementTree.fromstring(conn.getDomainCapabilities(emulator, arch, machine, domain, 0)) result = _parse_domain_caps(caps) finally: conn.close() return result def all_capabilities(**kwargs): ''' Return the host and domain capabilities in a single call. .. versionadded:: Neon :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.all_capabilities ''' conn = __get_conn(**kwargs) result = {} try: host_caps = ElementTree.fromstring(conn.getCapabilities()) domains = [[(guest.get('arch', {}).get('name', None), key) for key in guest.get('arch', {}).get('domains', {}).keys()] for guest in [_parse_caps_guest(guest) for guest in host_caps.findall('guest')]] flattened = [pair for item in (x for x in domains) for pair in item] result = { 'host': { 'host': _parse_caps_host(host_caps.find('host')), 'guests': [_parse_caps_guest(guest) for guest in host_caps.findall('guest')] }, 'domains': [_parse_domain_caps(ElementTree.fromstring( conn.getDomainCapabilities(None, arch, None, domain))) for (arch, domain) in flattened]} finally: conn.close() return result def cpu_baseline(full=False, migratable=False, out='libvirt', **kwargs): ''' Return the optimal 'custom' CPU baseline config for VM's on this minion .. versionadded:: 2016.3.0 :param full: Return all CPU features rather than the ones on top of the closest CPU model :param migratable: Exclude CPU features that are unmigratable (libvirt 2.13+) :param out: 'libvirt' (default) for usable libvirt XML definition, 'salt' for nice dict :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.cpu_baseline ''' conn = __get_conn(**kwargs) caps = ElementTree.fromstring(conn.getCapabilities()) cpu = caps.find('host/cpu') log.debug('Host CPU model definition: %s', salt.utils.stringutils.to_str(ElementTree.tostring(cpu))) flags = 0 if migratable: # This one is only in 1.2.14+ if getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_MIGRATABLE', False): flags += libvirt.VIR_CONNECT_BASELINE_CPU_MIGRATABLE else: conn.close() raise ValueError if full and getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # This one is only in 1.1.3+ flags += libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES cpu = ElementTree.fromstring(conn.baselineCPU([salt.utils.stringutils.to_str(ElementTree.tostring(cpu))], flags)) conn.close() if full and not getattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', False): # Try do it by ourselves # Find the models in cpu_map.xml and iterate over them for as long as entries have submodels with salt.utils.files.fopen('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map: cpu_map = ElementTree.parse(cpu_map) cpu_model = cpu.find('model').text while cpu_model: cpu_map_models = cpu_map.findall('arch/model') cpu_specs = [el for el in cpu_map_models if el.get('name') == cpu_model and bool(len(el))] if not cpu_specs: raise ValueError('Model {0} not found in CPU map'.format(cpu_model)) elif len(cpu_specs) > 1: raise ValueError('Multiple models {0} found in CPU map'.format(cpu_model)) cpu_specs = cpu_specs[0] # libvirt's cpu map used to nest model elements, to point the parent model. # keep this code for compatibility with old libvirt versions model_node = cpu_specs.find('model') if model_node is None: cpu_model = None else: cpu_model = model_node.get('name') cpu.extend([feature for feature in cpu_specs.findall('feature')]) if out == 'salt': return { 'model': cpu.find('model').text, 'vendor': cpu.find('vendor').text, 'features': [feature.get('name') for feature in cpu.findall('feature')] } return cpu.toxml() def network_define(name, bridge, forward, **kwargs): ''' Create libvirt network. :param name: Network name :param bridge: Bridge name :param forward: Forward mode(bridge, router, nat) :param vport: Virtualport type :param tag: Vlan tag :param autostart: Network autostart (default True) :param start: Network start (default True) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code-block:: bash salt '*' virt.network_define network main bridge openvswitch .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) vport = kwargs.get('vport', None) tag = kwargs.get('tag', None) autostart = kwargs.get('autostart', True) starting = kwargs.get('start', True) net_xml = _gen_net_xml( name, bridge, forward, vport, tag, ) try: conn.networkDefineXML(net_xml) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards try: network = conn.networkLookupByName(name) except libvirtError as err: log.warning(err) conn.close() raise err # a real error we should report upwards if network is None: conn.close() return False if (starting is True or autostart is True) and network.isActive() != 1: network.create() if autostart is True and network.autostart() != 1: network.setAutostart(int(autostart)) elif autostart is False and network.autostart() == 1: network.setAutostart(int(autostart)) conn.close() return True def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_networks ''' conn = __get_conn(**kwargs) try: return [net.name() for net in conn.listAllNetworks()] finally: conn.close() def network_info(name=None, **kwargs): ''' Return informations on a virtual network provided its name. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined virtual networks. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_info default ''' result = {} conn = __get_conn(**kwargs) def _net_get_leases(net): ''' Get all DHCP leases for a network ''' leases = net.DHCPLeases() for lease in leases: if lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4: lease['type'] = 'ipv4' elif lease['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV6: lease['type'] = 'ipv6' else: lease['type'] = 'unknown' return leases try: nets = [net for net in conn.listAllNetworks() if name is None or net.name() == name] result = {net.name(): { 'uuid': net.UUIDString(), 'bridge': net.bridgeName(), 'autostart': net.autostart(), 'active': net.isActive(), 'persistent': net.isPersistent(), 'leases': _net_get_leases(net)} for net in nets} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_start default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.create()) finally: conn.close() def network_stop(name, **kwargs): ''' Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close() def network_undefine(name, **kwargs): ''' Remove a defined virtual network. This does not stop the virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_undefine default ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.undefine()) finally: conn.close() def network_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a virtual network so that the network will start with the host system on reboot. :param name: virtual network name :param state: 'on' to auto start the network, anything else to mark the virtual network not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.network_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_define(name, ptype, target=None, permissions=None, source_devices=None, source_dir=None, source_adapter=None, source_hosts=None, source_auth=None, source_name=None, source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name **kwargs): ''' Create libvirt pool. :param name: Pool name :param ptype: Pool type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param target: Pool full path target :param permissions: Permissions to set on the target folder. This is mostly used for filesystem-based pool types. See pool-define-permissions_ for more details on this structure. :param source_devices: List of source devices for pools backed by physical devices. (Default: ``None``) Each item in the list is a dictionary with ``path`` and optionally ``part_separator`` keys. The path is the qualified name for iSCSI devices. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for more informations on the use of ``part_separator`` :param source_dir: Path to the source directory for pools of type ``dir``, ``netfs`` or ``gluster``. (Default: ``None``) :param source_adapter: SCSI source definition. The value is a dictionary with ``type``, ``name``, ``parent``, ``managed``, ``parent_wwnn``, ``parent_wwpn``, ``parent_fabric_wwn``, ``wwnn``, ``wwpn`` and ``parent_address`` keys. The ``parent_address`` value is a dictionary with ``unique_id`` and ``address`` keys. The address represents a PCI address and is itself a dictionary with ``domain``, ``bus``, ``slot`` and ``function`` properties. Report to `this libvirt page <https://libvirt.org/formatstorage.html#StoragePool>`_ for the meaning and possible values of these properties. :param source_hosts: List of source for pools backed by storage from remote servers. Each item is the hostname optionally followed by the port separated by a colon. (Default: ``None``) :param source_auth: Source authentication details. (Default: ``None``) The value is a dictionary with ``type``, ``username`` and ``secret`` keys. The type can be one of ``ceph`` for Ceph RBD or ``chap`` for iSCSI sources. The ``secret`` value links to a libvirt secret object. It is a dictionary with ``type`` and ``value`` keys. The type value can be either ``uuid`` or ``usage``. Examples: .. code-block:: python source_auth={ 'type': 'ceph', 'username': 'admin', 'secret': { 'type': 'uuid', 'uuid': '2ec115d7-3a88-3ceb-bc12-0ac909a6fd87' } } .. code-block:: python source_auth={ 'type': 'chap', 'username': 'myname', 'secret': { 'type': 'usage', 'uuid': 'mycluster_myname' } } :param source_name: Identifier of name-based sources. :param source_format: String representing the source format. The possible values are depending on the source type. See `libvirt documentation <https://libvirt.org/storage.html>`_ for the possible values. :param start: Pool start (default True) :param transient: When ``True``, the pool will be automatically undefined after being stopped. Note that a transient pool will force ``start`` to ``True``. (Default: ``False``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. _pool-define-permissions: **Permissions definition** The permissions are described by a dictionary containing the following keys: mode The octal representation of the permissions. (Default: `0711`) owner the numeric user ID of the owner. (Default: from the parent folder) group the numeric ID of the group. (Default: from the parent folder) label the SELinux label. (Default: `None`) CLI Example: Local folder pool: .. code-block:: bash salt '*' virt.pool_define somepool dir target=/srv/mypool \ permissions="{'mode': '0744' 'ower': 107, 'group': 107 }" CIFS backed pool: .. code-block:: bash salt '*' virt.pool_define myshare netfs source_format=cifs \ source_dir=samba_share source_hosts="['example.com']" target=/mnt/cifs .. versionadded:: 2019.2.0 ''' conn = __get_conn(**kwargs) pool_xml = _gen_pool_xml( name, ptype, target, permissions=permissions, source_devices=source_devices, source_dir=source_dir, source_adapter=source_adapter, source_hosts=source_hosts, source_auth=source_auth, source_name=source_name, source_format=source_format ) try: if transient: pool = conn.storagePoolCreateXML(pool_xml) else: pool = conn.storagePoolDefineXML(pool_xml) if start: pool.create() except libvirtError as err: raise err # a real error we should report upwards finally: conn.close() # libvirt function will raise a libvirtError in case of failure return True def list_pools(**kwargs): ''' List all storage pools. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.list_pools ''' conn = __get_conn(**kwargs) try: return [pool.name() for pool in conn.listAllStoragePools()] finally: conn.close() def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults If no name is provided, return the infos for all defined storage pools. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_info default ''' result = {} conn = __get_conn(**kwargs) def _pool_extract_infos(pool): ''' Format the pool info dictionary :param pool: the libvirt pool object ''' states = ['inactive', 'building', 'running', 'degraded', 'inaccessible'] infos = pool.info() state = states[infos[0]] if infos[0] < len(states) else 'unknown' desc = ElementTree.fromstring(pool.XMLDesc()) path_node = desc.find('target/path') return { 'uuid': pool.UUIDString(), 'state': state, 'capacity': infos[1], 'allocation': infos[2], 'free': infos[3], 'autostart': pool.autostart(), 'persistent': pool.isPersistent(), 'target_path': path_node.text if path_node is not None else None, 'type': desc.get('type') } try: pools = [pool for pool in conn.listAllStoragePools() if name is None or pool.name() == name] result = {pool.name(): _pool_extract_infos(pool) for pool in pools} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def pool_start(name, **kwargs): ''' Start a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_start default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.create()) finally: conn.close() def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_build default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.build()) finally: conn.close() def pool_stop(name, **kwargs): ''' Stop a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_stop default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.destroy()) finally: conn.close() def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_undefine default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.undefine()) finally: conn.close() def pool_delete(name, fast=True, **kwargs): ''' Delete the resources of a defined libvirt storage pool. :param name: libvirt storage pool name :param fast: if set to False, zeroes out all the data. Default value is True. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_delete default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) flags = libvirt.VIR_STORAGE_POOL_DELETE_NORMAL if fast: flags = libvirt.VIR_STORAGE_POOL_DELETE_ZEROED return not bool(pool.delete(flags)) finally: conn.close() def pool_refresh(name, **kwargs): ''' Refresh a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.pool_refresh default ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.refresh()) finally: conn.close() def pool_set_autostart(name, state='on', **kwargs): ''' Set the autostart flag on a libvirt storage pool so that the storage pool will start with the host system on reboot. :param name: libvirt storage pool name :param state: 'on' to auto start the pool, anything else to mark the pool not to be started when the host boots :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_set_autostart <pool> <on | off> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return not bool(pool.setAutostart(1 if state == 'on' else 0)) finally: conn.close() def pool_list_volumes(name, **kwargs): ''' List the volumes contained in a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt "*" virt.pool_list_volumes <pool> ''' conn = __get_conn(**kwargs) try: pool = conn.storagePoolLookupByName(name) return pool.listVolumes() finally: conn.close() def _get_storage_vol(conn, pool, vol): ''' Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found. ''' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol) def _is_valid_volume(vol): ''' Checks whether a volume is valid for further use since those may have disappeared since the last pool refresh. ''' try: # Getting info on an invalid volume raises error vol.info() return True except libvirt.libvirtError as err: return False def _get_all_volumes_paths(conn): ''' Extract the path and backing stores path of all volumes. :param conn: libvirt connection to use ''' volumes = [vol for l in [obj.listAllVolumes() for obj in conn.listAllStoragePools()] for vol in l] return {vol.path(): [path.text for path in ElementTree.fromstring(vol.XMLDesc()).findall('.//backingStore/path')] for vol in volumes if _is_valid_volume(vol)} def volume_infos(pool=None, volume=None, **kwargs): ''' Provide details on a storage volume. If no volume name is provided, the infos all the volumes contained in the pool are provided. If no pool is provided, the infos of the volumes of all pools are output. :param pool: libvirt storage pool name (default: ``None``) :param volume: name of the volume to get infos from (default: ``None``) :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_infos <pool> <volume> ''' result = {} conn = __get_conn(**kwargs) try: backing_stores = _get_all_volumes_paths(conn) domains = _get_domain(conn) domains_list = domains if isinstance(domains, list) else [domains] disks = {domain.name(): {node.get('file') for node in ElementTree.fromstring(domain.XMLDesc(0)).findall('.//disk/source/[@file]')} for domain in domains_list} def _volume_extract_infos(vol): ''' Format the volume info dictionary :param vol: the libvirt storage volume object. ''' types = ['file', 'block', 'dir', 'network', 'netdir', 'ploop'] infos = vol.info() # If we have a path, check its use. used_by = [] if vol.path(): as_backing_store = {path for (path, all_paths) in backing_stores.items() if vol.path() in all_paths} used_by = [vm_name for (vm_name, vm_disks) in disks.items() if vm_disks & as_backing_store or vol.path() in vm_disks] return { 'type': types[infos[0]] if infos[0] < len(types) else 'unknown', 'key': vol.key(), 'path': vol.path(), 'capacity': infos[1], 'allocation': infos[2], 'used_by': used_by, } pools = [obj for obj in conn.listAllStoragePools() if pool is None or obj.name() == pool] vols = {pool_obj.name(): {vol.name(): _volume_extract_infos(vol) for vol in pool_obj.listAllVolumes() if (volume is None or vol.name() == volume) and _is_valid_volume(vol)} for pool_obj in pools} return {pool_name: volumes for (pool_name, volumes) in vols.items() if volumes} except libvirt.libvirtError as err: log.debug('Silenced libvirt error: %s', str(err)) finally: conn.close() return result def volume_delete(pool, volume, **kwargs): ''' Delete a libvirt managed volume. :param pool: libvirt storage pool name :param volume: name of the volume to delete :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: Neon CLI Example: .. code-block:: bash salt "*" virt.volume_delete <pool> <volume> ''' conn = __get_conn(**kwargs) try: vol = _get_storage_vol(conn, pool, volume) return not bool(vol.delete()) finally: conn.close()